STRING INSTANCE METHODS
Java String repeat() method
repeat() returns a string containing the original String repeated a specified number of times. The original string stays unchanged. The method is available since Java 11.
Repeating a string
String tekstas = "abc";
int kiekis = 3;
String rezultatas = tekstas.repeat(kiekis);
System.out.println(rezultatas);abcabcabc
- The variable
tekstasstores the three-letter string abc. - The variable
kiekisspecifies the total number of repetitions:3. repeat(kiekis)concatenates three copies of abc without extra spaces.- The result abcabcabc is assigned to a variable and printed.
Why is repeat() an instance method?
repeat() is called on a specific String object because it repeats that object’s text. The only argument is the repetition count.
String rezultatas = tekstas.repeat(3);
We do not write String.repeat(tekstas, 3), because this is not a static method. It can also be called directly on a string literal: "abc".repeat(3).
Method syntax
public String repeat(int count)
| Part | Meaning |
|---|---|
| Calling object | String – The string to repeat. |
| Parameter | count – The int repetition count. It must be 0 or greater. |
| Return type | String – The repeated string. |
| Zero count | 0 – Returns an empty string. |
| Negative count | IllegalArgumentException – Thrown when the repetition count is negative. |
| Java version | 11 – The method was introduced in Java 11. |
The parameter count is the total number of copies, rather than the number of extra copies. For example, repeat(3) produces three copies, rather than four.
When the repetition count is 0
String tekstas = "xyz";
String rezultatas = tekstas.repeat(0);
System.out.println("[" + rezultatas + "]");
System.out.println(rezultatas.length());
System.out.println(rezultatas.isEmpty());[]
0
true
Zero means that no copies of the original string are included. The result is an empty string, rather than null or an exception. The square brackets in the output make the absence of characters visible.
When the repetition count is 1
String tekstas = "Java";
String rezultatas = tekstas.repeat(1);
System.out.println(rezultatas);
System.out.println(rezultatas.equals(tekstas));Java
true
One repetition returns the same text content as the original string. We use equals(), rather than ==, to compare the content.
Repeating an empty string
String tekstas = "";
System.out.println("[" + tekstas.repeat(5) + "]");
System.out.println(tekstas.repeat(5).length());[]
0
Repeating an empty string with a nonnegative count always produces an empty string. Even many empty copies add no characters. A negative count still throws IllegalArgumentException.
repeat() does not change the original string
String tekstas = "Java";
tekstas.repeat(3);
System.out.println(tekstas);
tekstas = tekstas.repeat(3);
System.out.println(tekstas);Java
JavaJavaJava
String is immutable. The first repeat(3) result is not assigned, so the variable still stores Java. The second call assigns the result back to the variable, making it available for later use.
Spaces are not added automatically
System.out.println("[" + "Java".repeat(3) + "]");
System.out.println("[" + "Java ".repeat(3) + "]");[JavaJavaJava]
[Java Java Java ]
The method repeats the original string exactly. If it includes a space, that space is repeated too, including after the final word. repeat() has no separate delimiter parameter.
Practical example: a separator and indentation
String skirtukas = "-".repeat(12);
String itrauka = " ".repeat(4);
System.out.println(skirtukas);
System.out.println(itrauka + "JavaQuest");
System.out.println(skirtukas);------------
JavaQuest
------------
Repeating a hyphen 12 times produces a separator line. Four spaces indent JavaQuest. This is useful for console reports, table headings, and simple text formatting.
Using repeat() in a loop
for (int eilute = 1; eilute <= 4; eilute++) {
System.out.println("*".repeat(eilute));
}*
**
***
****
The repetition count increases by one on each iteration, so each output line contains more stars. No inner loop is needed to repeat the same character.
A negative count throws IllegalArgumentException
String tekstas = "Java";
System.out.println(tekstas.repeat(-1));IllegalArgumentException
A string cannot be repeated a negative number of times. Java throws IllegalArgumentException rather than returning an empty string. This also applies when the original string is empty.
Validating the repetition count
String tekstas = "ab";
int kiekis = 3;
int didziausiasKiekis = 100;
if (kiekis >= 0 && kiekis <= didziausiasKiekis) {
System.out.println(tekstas.repeat(kiekis));
} else {
System.out.println(false);
}ababab
When the count comes from user input, validate both a lower and an upper bound. This example allows 0 through 100 repetitions. That is an example application rule, rather than a Java limit on repeat().
The result length grows with both the original string length and the repetition count. A very large result can exhaust memory and cause OutOfMemoryError. Choose a limit based on the expected text size and the needs of the application.
Differences between repeat(), concat(), and StringBuilder
String tekstas = "ab";
System.out.println(tekstas.repeat(3));
System.out.println(tekstas.concat("cd"));
StringBuilder rezultatas = new StringBuilder();
for (int i = 0; i < 3; i++) {
rezultatas.append(tekstas);
}
System.out.println(rezultatas.toString());ababab
abcd
ababab
repeat() repeats the same string a specified number of times. concat() appends another string once. StringBuilder is useful when a loop combines different parts or the content changes between iterations. Java 8 does not provide repeat(); a StringBuilder and loop can perform this repetition.
The method cannot be called on null
String tekstas = null;
System.out.println(tekstas.repeat(3));NullPointerException
null means that no String object exists, so there is no text to repeat. This call throws NullPointerException. An empty string is a valid String object and differs from null.
Common mistakes
- Expecting
repeat()to change the original string and leaving its result unassigned. - Treating the repetition count as the number of additional copies.
- Passing a negative count or a count that is too large for the application.
- Calling
repeat()on anullreference or trying to use it in Java 8.
When should you use repeat()?
Use repeat() when you need multiple copies of the same text: separators, indentation, simple patterns, or test data. Use StringBuilder when each part differs, or String.join() to combine existing strings with a delimiter.