This example shows 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.util;
import java.util.Arrays;
public class RepeatCharacterExample {
public static void main(String[] args) {
char c = '*';
int length = 10;
// creates a char array with 10 elements
char[] chars = new char[length];
// fill each element of the char array with '*'
Arrays.fill(chars, c);
// print out the repeated '*'
System.out.println(String.valueOf(chars));
}
}
As the result you get the x
character repeated 10 times.
**********
For one-liner code, you can use the following code snippet, which will give you the same result.
public class Test {
public static void main(String[] args) {
String str = new String(new char[10]).replace('\u0000', '*');
}
}
Or
import java.util.Collections;
public class Test {
public static void main(String[] args) {
String str = String.join("", Collections.nCopies(10, "*"));
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024