Note that there are some explanatory texts on larger screens.

plurals
  1. POSimple way to repeat a String in java
    text
    copied!<p>I'm looking for a simple commons method or operator that allows me to repeat some String <em>n</em> times. I know I could write this using a for loop, but I wish to avoid for loops whenever necessary and a simple direct method should exist somewhere.</p> <pre><code>String str = "abc"; String repeated = str.repeat(3); repeated.equals("abcabcabc"); </code></pre> <p><strong>Related to:</strong></p> <p><a href="https://stackoverflow.com/questions/202605/repeat-string-javascript">repeat string javascript</a> <a href="https://stackoverflow.com/questions/260945/create-nsstring-by-repeating-another-string-a-given-number-of-times">Create NSString by repeating another string a given number of times</a></p> <p><strong>Edited</strong></p> <p>I try to avoid for loops when they are not completely necessary because:</p> <ol> <li><p>They add to the number of lines of code even if they are tucked away in another function.</p></li> <li><p>Someone reading my code has to figure out what I am doing in that for loop. Even if it is commented and has meaningful variables names, they still have to make sure it is not doing anything "clever".</p></li> <li><p>Programmers love to put clever things in for loops, even if I write it to "only do what it is intended to do", that does not preclude someone coming along and adding some additional clever "fix".</p></li> <li><p>They are very often easy to get wrong. For loops involving indexes tend to generate off by one bugs.</p></li> <li><p>For loops often reuse the same variables, increasing the chance of really hard to find scoping bugs.</p></li> <li><p>For loops increase the number of places a bug hunter has to look.</p></li> </ol>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload