Skip to content

Instantly share code, notes, and snippets.

@umidjons
Created April 16, 2014 11:49
Show Gist options
  • Save umidjons/10859940 to your computer and use it in GitHub Desktop.
Save umidjons/10859940 to your computer and use it in GitHub Desktop.
Repeat string N times without loop in Java

Repeat string N times without loop in Java

package javaapplication1;
public class JavaApplication1 {
    /**
     * Repeat string <b>str</b> <b>times</b> time.
     * @param str string to repeat
     * @param times repeat str times time
     * @return generated string
     */
    public static String repeat(String str, int times) {
        return new String(new char[times]).replace("\0", str);
    }
    public static void main(String[] args) {
        System.out.println(repeat("*", 5));
    }

}
@jn48
Copy link

jn48 commented Jan 18, 2016

Thanks for writing this. Would you mind explaining why this works? Thanks!

@codepenman
Copy link

But the loop happens internally, right ? What you are trying to avoid is the external loop. Am I correct ?

@MeHelmy
Copy link

MeHelmy commented Mar 4, 2016

Primitive types (char[], in this case) are instantiated with nulls "number of times", then a String is created from the char[], and the nulls are replaced() with the character you want in str

@manikantag
Copy link

manikantag commented Apr 30, 2018

If you've Apache 'commons-lang3' already in classpath, org.apache.commons.lang3.StringUtils.repeat(...) methods use similar technique.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment