Java repeat string without using loops


 

Java repeat string without using loops

In this section, you will learn how to repeat string without using for loops.

In this section, you will learn how to repeat string without using for loops.

Java repeat string without using loops

In this section, you will learn how to repeat string without using for loops.

The given example accepts the number of times and iterates the string to the number of times set by the user without using while loop or any other control statements.

Example:

import java.util.*;
class RepeatString 
{
	public static String repeat(String str, int times){
   return new String(new char[times]).replace("\0", str);
}

	public static void main(String[] args) 
	{
		Scanner input=new Scanner(System.in);
		System.out.println("Enter no. of times: ");
		int no=input.nextInt();
		String st="Hello World";
        System.out.println(repeat(st+"\n", no));

	}
}

Output:

Enter no. of times:
5
Hello World
Hello World
Hello World
Hello World
Hello World

Ads