March 6, 2022

Java String repeat() Method

If you want to repeat a String n number of times from Java 11 there is a repeat() method in String class to do that.

public String repeat(int count)- Returns a string whose value is the concatenation of this string repeated count times. If this string is empty or count is zero then the empty string is returned.

String repeat() method example

public class App {
  public static void main( String[] args ){
    String str = "Test";
    System.out.println(str.repeat(4));      
  }
}
Output
TestTestTestTest

Option to repeat string till Java 10

Since repeat() method is added in Java 11 so before that using replace() method of the Java String class you could repeat the String.

There are overloaded versions of replace method but you can use the following one. You can also use replaceAll() instead.

replace(CharSequence target, CharSequence replacement)- Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.

Logic of the program uses the fact that when you create an array it is initialized with default values. For char array the default value is ‘\u0000’. So you create a char array with size equal to the number of times String has to be repeated. Use replace method to replace default value (‘\u0000’) with the string.

public class App {
  public static void main( String[] args ){
    String str = "Test";
    // replace every occurrence of \u0000 with str
    String repeatStr = new String(new char[4]).replace("\u0000" , str);
    System.out.println(repeatStr);
  }
}
Output
TestTestTestTest

That's all for the topic Java String repeat() Method. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment