Repeat string

This example will show how to repeat a string for a given number of times using java, guava and apache commons.

Straight up Java

Char array

@Test
public void repeat_a_string_java_with_char_array() {

    int numberOfTimesToRepeat = 3;
    String uppityup = new String(new char[numberOfTimesToRepeat]).replace(
            "\0", "up");

    assertEquals("upupup", uppityup);
}

For loop

With each iteration of a for loop we will append to a StringBuilder a specified number of times repeating a string.

@Test
public void repeat_a_string_java_with_loop() {

    int numberOfTimesToRepeat = 3;
    StringBuilder uppityup = new StringBuilder();
    for (int x = 0; x < numberOfTimesToRepeat; x++) {
        uppityup.append("up");
    }

    assertEquals("upupup", uppityup.toString());
}

Google Guava

Guava Strings.repeat will concatenate an input String a specific number of times.

@Test
public void repeat_a_string_with_guava () {
    
    String uppityup = Strings.repeat("up", 3);
    assertEquals("upupup", uppityup);
}

Apache Commons

Apache commons will repeat a String a specified number of times to form a new String.

@Test
public void repeat_a_string_with_apache_commons () {

    String uppityup = StringUtils.repeat("up", 3);
    assertEquals("upupup", uppityup);
}