Home Tutorial Java Core Java repeat string without using loops

 
 

Share on Google+Share on Google+
Java repeat string without using loops
Posted on: October 5, 2012 at 12:00 AM
Advertisement
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
Advertisement

Related Tags for Java repeat string without using loops:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 5, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com