How to simply and efficiently repeat a string in Java?
Hi everyone! I'm a beginner Java developer and I have a problem. I need to repeat the same string multiple times, for example, the character '-' 10 times to draw a separator line in the console. Or, say, repeat the word "Hello" 5 times to get "HelloHelloHelloHelloHello".
I know that I can do it manually using a loop:
```java
String str = "Hello";
String result = "";
for (int i = 0; i < 5; i++) {
result += str;
}
System.out.println(result); // HelloHelloHelloHelloHello
```
But this looks cumbersome and ugly. Moreover, I've heard that string concatenation in a loop using `+=` is bad practice because a new String object is created each time. For large repetitions, this will be slow.
I tried using `StringBuilder`, but the code
No answers yet.
Log in to leave an answer
Blogs