This example show you how to create a repeated sequence of characters. To do this we use the Arrays.fill()
method. This method fills an array of char
with a character.
package org.kodejava.example.util;
import java.util.Arrays;
public class RepeatCharacterExample {
public static void main(String[] args) {
char c = 'x';
int length = 10;
// creates char array with 10 elements
char[] chars = new char[length];
// fill each element of chars array with 'x'
Arrays.fill(chars, c);
// print out the repeated 'x'
System.out.println(String.valueOf(chars));
}
}
As the result you get the x
character repeated 10 times.
xxxxxxxxxx
For one liner code you can use the following code snippet, which will give you the same result.
new String(new char[10]).replace('\u0000', 'x');
Or
String.join("", Collections.nCopies(10, "x"));
Latest posts by Wayan (see all)
- How do I create a generic class in Java? - January 1, 2021
- How do I convert java.util.TimeZone to java.time.ZoneId? - April 25, 2020
- How do I get a list of all TimeZones Ids using Java 8? - April 25, 2020