repeat method in java code example
Example 1: repeat string in java
public class Main
{
public static void main(String[] args)
{
String str = "Abc";
String repeated = new String(new char[3]).replace("\0", str);
System.out.println(repeated);
}
}
Example 2: how to write a method that returns a string that copies itself times n
public static String repeat(String s, int n) { StringBuilder sb = new StringBuilder(str.length() * n); for (int i = 0; i < n; i++) sb.append(s); return sb.toString();} public static void main(String[] args) { System.out.println(repeat("ha", 5));}