Print a string N number of times in Java
In this tutorial, we will see – How to Print a string N number of times in Java using various methods.
A string is a sequence of characters. The String class in Java is used to create and implement string objects. It basically has the implementation of a character array.
Printing a string N times
We can do this in various ways. Some of them are:
- Using for loop
- Taking input for N
- Using the repeat() method
Print a string N number of times, once in each line in Java
my_string: CodeSpeedy N: 5 Output: CodeSpeedy CodeSpeedy CodeSpeedy CodeSpeedy CodeSpeedy
Java Code for this is as follows
public class Main
{
public static void main(String[] args) {
String my_string = "CodeSpeedy";
int N = 5;
//print once in each line
for (int i =0; i<5; i++){
System.out.println(my_string);
}
}
}Print a string N number of times in a single line in Java
my_string: CodeSpeedy N: 4 Output: CodeSpeedyCodeSpeedyCodeSpeedyCodeSpeedy
Java Code for this is as follows
public class Main
{
public static void main(String[] args) {
String my_string = "CodeSpeedy";
int N = 5;
//print N times in one line
for (int i =0; i<5; i++){
System.out.print(my_string);
}
}
}Taking input for N
We can take input in Java using the Java Scanner class of java.util.Scanner.
Input:
my_string: Java is Fun!
N: 3
Output: Printing the string N times in a single line.
Java is Fun!Java is Fun!Java is Fun!
Printing the string N times, once in each line
Java is Fun!
Java is Fun!
Java is Fun!Java Code for this is as follows
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner a = new Scanner(System.in);
System.out.print("my_string: ");
String my_string = a.nextLine();
System.out.print("N: ");
int N = a.nextInt();
System.out.println("Printing the string" + N + "times in a single line.");
for (int i =0; i<5; i++){
System.out.print(my_string);
}
System.out.println("\n\nPrinting the string" + N + "times, once in each line");
for (int i =0; i<5; i++){
System.out.println(my_string);
}
}
}Using the repeat() method
Java11 has a method to do this very easily. We can use the repeat() method of org.apache.commons.lang3 package for this. The method can be used as my_string.repeat(n)
Input:
my_string: Java 11.
N: 4
Output: Java 11.Java 11.Java 11.Java 11.Java Code for this is as follows
import org.apache.commons.lang3.StringUtils;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner a = new Scanner(System.in);
System.out.print("my_string: ");
String my_string = a.nextLine();
System.out.print("N: ");
int N = a.nextInt();
String repeated = my_string.repeat(3);
System.out.print(repeated);
}
}You may also like :
How to print even length words in a String
Leave a Reply