I'm coming from a Python background where I can simply use the multiplication operator to repeat a string. In Java, I've been using a for-loop with a StringBuilder to concatenate the same word five or ten times, but it feels overly verbose for such a basic task. Is there a built-in method in the newer versions of the JDK (like Java 11 or 17) that allows for a cleaner, more readable one-liner to handle string repetition?
3 answers
If you are using Java 11 or any version above it, the simplest way is to use the built-in String.repeat(int count) method. For example, if you want to repeat the word "Hello" three times, you just write "Hello".repeat(3);. This returns a new string containing the original string repeated the specified number of times. It is much more efficient than manual concatenation in a loop because it calculates the total size of the final array upfront, avoiding multiple memory reallocations. It also handles edge cases, such as passing a count of zero (which returns an empty string) or a negative count (which throws an IllegalArgumentException).
Does this repeat() method work well for very large counts, or should I still stick to StringBuilder if I’m trying to create a massive block of text, say repeating a character 100,000 times? I've heard that for extremely large buffers, the internal implementation of certain methods can still lead to OutOfMemoryError if not handled carefully.
For those stuck on Java 8 or older, you can't use .repeat(). Your best bet is using Collections.nCopies(n, str) and then joining them with String.join("", list). It's a bit of a workaround but keeps it to a couple of lines.
I agree with Melissa. That nCopies trick is clever for legacy systems. I remember using a similar hack with Apache Commons StringUtils.repeat() before we finally upgraded our servers to Java 11. It's always good to have a backup plan for older environments!
Kevin, for 100,000 repetitions, String.repeat() is actually quite optimized because it uses System.arraycopy() internally. However, if you are building a larger document where the repeated string is just one part of the puzzle, you should definitely stick with StringBuilder. Using repeat() creates a brand new String object in memory, whereas StringBuilder allows you to append that repeated sequence directly into an existing buffer. If memory overhead is your primary concern in a high-concurrency app, manual buffering is still the safer, more surgical approach.