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

Related Posts

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

One Comment

  1. What is the Iterator Design Pattern?
    A container can be a list, set, multiset, trees, and graphs, and by underlying representation we mean the way the container has been composed with its methods and properties. If you have come across iterators or “iterables” before, they are in a more general sense something that can be looped over, using a standard loop. “So, what is new in this?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.