Java 11 adds a new method called repeat
to the String class. The repeat
method returns a new string whose value is the concatenation of this string repeated n
times, where n
is passed as an argument.
public String repeat(int n)
// n -- The number of times the string needs to be repeated
public class Main{public static void main(String[] args) {String str = ". ";System.out.println( str.repeat(5) ); //. . . . .}}// the above method will return a new string with ". " repeated five times//. . . . .
The above code can be tested online here.
Points to note
If n = 0
, then an empty string is returned.
If n = 1
, then a reference to the original string is returned.
If n < 0
, then IllegalArgumentException
is thrown.
If the string is empty, then the repeat method will return an empty string for all positive n
values.
If the resulting string is too big, then OutOfMemoryError
exception will be thrown.
All the above cases are covered in the example below.
public class HelloWorld {public static void main(String[] args) {String str = "test";System.out.println("Passing n = 0 will return an empty string" + str.repeat(0));String oneTimeRepeatedString = str.repeat(1);System.out.println("Passing n = 1 will return a reference to this string " + oneTimeRepeatedString);System.out.println("Checking if references are equal by str == oneTimeRepeatedString " + (oneTimeRepeatedString == str) );try {System.out.println("Passing n < 0 will throw an IllegalArgumentException" + str.repeat(-1));} catch(Exception e) {System.out.println(e);}try {System.out.println("Passing larger n values will throw an OutOfMemoryError" + str.repeat(Integer.MAX_VALUE));} catch(Exception e) {System.out.println(e);}}}
You can execute the above code online here.