Share on Google+Share on Google+

Java repeat string without using loops

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

Advertisements

Posted on: October 5, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial 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.