The following code demonstrates how to create a string of repeated characters. We use the String.repeat(int count)
method introduced in Java 11. This method takes one parameter of type int
which is the number of times to repeat the string. The count
must be a positive number, a negative number will cause this method to throw java.lang.IllegalArgumentException
.
In the snippet below, we use the method to repeat characters and draw some triangles. We combine the repeat()
method with a for loop to draw the triangles.
package org.kodejava.basic;
public class StringRepeatDemo {
public static void main(String[] args) {
String star = "*";
String fiveStars = star.repeat(5);
System.out.println("fiveStars = " + fiveStars);
String arrow = "-->";
String arrows = arrow.repeat(10);
System.out.println("arrows = " + arrows);
}
}
The outputs of the code snippet above are:
fiveStars = *****
arrows = -->-->-->-->-->-->-->-->-->-->
package org.kodejava.basic;
public class StringRepeatDemo {
public static void main(String[] args) {
String asterisk = "#";
for (int i = 1; i <= 10; i++) {
System.out.println(asterisk.repeat(i));
}
}
The outputs of the code snippet above are:
#
##
###
####
#####
######
#######
########
#########
##########
package org.kodejava.basic;
public class StringRepeatDemo {
public static void main(String[] args) {
int height = 10;
for (int i = 1, j = 1; i <= height; i++, j += 2) {
System.out.println(" ".repeat(height - i) + "*".repeat(j));
}
}
}
The outputs of the code snippet above are:
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
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