Java String repeat Example

1. Introduction

This blog post explores the repeat() method in Java's String class. Introduced in Java 11, repeat() is a method that replicates a string a specified number of times, making it easier to repeat strings without loops.

Definition

String.repeat(int count) is a method that constructs and returns a new string which is the concatenation of the original string repeated count times. If count is zero, it returns an empty string.

2. Program Steps

1. Create a string to be repeated.

2. Use the repeat() method to repeat the string a specific number of times.

3. Display the repeated string.

3. Code Program

public class StringRepeatExample {
    public static void main(String[] args) {
        String originalString = "Java! ";

        // Repeating the string 3 times
        String repeatedString = originalString.repeat(3);

        // Displaying the repeated string
        System.out.println("Repeated String: " + repeatedString);
    }
}

Output:

Repeated String: Java! Java! Java!

Explanation:

1. originalString is defined as "Java! ".

2. The repeat(3) method is called on originalString, which creates a new string by repeating the original string three times.

3. The output displays "Java! Java! Java! ", showing the result of the repeat operation.

4. This example demonstrates the simplicity and utility of String.repeat(), allowing for easy replication of strings without the need for manual loops or additional logic.


Comments