Java – Repeat String for N times

To repeat a given string for specific number of times in Java, you can use a For loop statement to iterate for n number of times, and during each iteration, concatenate the given string to the resulting string.

1. Repeat the string “Apple” for 5 times using For loop in Java

In this example, we take a string "Apple" in str and repeat this string for five times to get "AppleAppleAppleAppleApple" as resulting string, using For loop.

Java Program

</>
Copy
public class Main {
	public static void main(String[] args) {
		String str = "Apple";
        int n = 5;
        
		// Repeat string n times
        String repeatedString = "";
		for(var i=0; i<n; i++) {
			repeatedString += str; 
		}
		
		System.out.println(repeatedString);
	}
}

Output

AppleAppleAppleAppleApple

Conclusion

In this Java String tutorial, we have seen how to repeat a given string for n number of times in Java using a For loop, with examples.