Repeat String N times in Java

Introduction

In this article, we will learn how to Repeat a given String N times in Java . This is a trick question common in JAVA interviews and the candidate’s evaluation is based on different approaches he/she provides for the problem.

So we will take a deep dive into looking at various ways to solve this problem, starting from the simplest approach to digging deep into how many approaches to ace our concepts. Let us first look at a quick glimpse of Strings in Java.

What is a String in Java?

String in general is a sequence of characters. In Java, String can be represented as an Object and a Literal. Using the String Object we can use the common utility methods provided by the String Class. Let us look at the syntax of declaring a String.

String as an object :

String as a literal or variable :

Note: We can also use the standard utility methods of the String Class with String literals, but the modifications will not reflect in the actual variable. This explains the Immutability of String in Java.

Repeat String N times in Java

Now, without further ado let us outline different ways to solve this problem and explain each method in detail with examples.

Simple For Loop to Repeat String N Times in Java

We can repeat String N times using a for loop in java. This is an iterative way to solve this problem. There are some points to note:

  • We take the input string str and a variable string result which will contain the resultant string.
  • We will run a loop N times that is given as input.
  • On each iteration we will concatenate the result string with the given string like this: result = result + str

In this way, we will have our resultant string repeated N times. Let us understand this with a code snippet.

Output:

Using Recursion to Repeat String N Times in Java

Given that we have to repeat a String that involves repeating a process over and over again, we can surmise that Recursion will be helpful to solve this problem. Important points to note:

  • If the input String is null or the counter N = 0, we simply return the string.
  • Otherwise, we return the input string and concatenate it with the value returned by the recursive call.
  • While making each recursive call we decrease the counter N to reach the base condition.

Let us look at the code snippet.

Output:

String.format() method to Repeat String N Times in Java

The String class in Java has some very useful methods to represent a String in various ways. The format() method of the String class is a method that returns a String in a specific format provided in the arguments. The syntax of the method is :

public static String format(String format, Object... args)

Important points to note:

  • In the format() method we pass the String as a text to format a number 0 to repeat N times.
  • We provide the parameter as ‘0’ to which we convert it to repeat N times.
  • Then, we replace the formatted string with the original string.

Let us look at the code implementation.

Output:

Using String.repeat() method in Java 11 to Repeat String N Times

With the introduction of Java 11, a new utility method was added to the String class -> repeat() method. With the repeat() method in the picture, we could repeat any String just by calling the method with the String variable name.

It takes only positive integer values as a parameter and returns a String that is repeated the specified times. The method throws IllegalArgumentException if the count is negative.

Syntax of the method:

public String repeat(int count)

Note: JDK 11.0 or higher must be installed on your machine to use this API.

Output:

Regular Expression – Regex to Repeat String N Times in Java

In Java, with the String replace() method we can define a Regular expression or a regex to modify any String.

Important Points to note:

  • We will create a String using a character or char array of length N, that is the number of times we want the String to repeat.
  • Next, we will replace each value in the array with the input String.
  • Since the default value of each element in the char array is null we replace ‘\0’ with our input String.

Let us have a look at the code snippet.

Output:

Collections.nCopies() method to Repeat String N Times in Java

With the advent of Java 8, the Collection Framework was introduced in java. Along with this, the Collections class was introduced that provided static methods to operate on the Collection and return the collection.

The nCopies() method of the Collections class generates n number of copies of any object type. It accepts two parameters: n -> the number of copies to make and the object to copy.

The syntax of the method:

T is the generic type. Ex: String, Object, etc.

Important Points to note:

  • The nCopies() method returns an Immutable list of objects. We pass the String to make copies of it.
  • After this we join each element in the returned list using the String.join() method.
  • We pass "" empty braces as the delimiter to the join() method so the repeats consecutively.

Let us look at the code implementation for this.

Output:

Using Stream API to Repeat String N Times in Java

In Java 8, the introduction of the Stream API and Lambda expressions helped in minimizing the code and add more features of functional programming.

Important points to note:

  • We use the Stream.generate() method as a Lambda expression and pass the input string as a parameter to generate copies of it. We use the limit() method to limit the number of copies to generate.
  • We use the collect() method to collect all the copies of the string.
  • To join them use the joining() method of the Collectors class inside the collect() method.

Let us look at the code snippet.

Output:

StringUtils Package – Apache Commons Library to Repeat String N Times in Java

The Apache Commons API provides powerful and reusable Java components and dependencies that we can embed into our applications and programs. Here, to repeat a String N times we can use the inbuilt functionality of this package.

We can use the StringUtils class of the Apache Commons Library by importing with the following dependency. For our ease, we will use the JAR file component of the Apache Commons Lang package.

To set up the JAR file component for this package we follow the steps mentioned here.

After this, we can just use the import statement to embed the StringUtils class from the Apache Commons Lang package. The StringUtils class provides the repeat() method as well to repeat a particular input String as we saw in earlier examples.

Let us look at the code for this as well.

Output:

That’s all for the post, we took a deep dive into various methods that one can use to Repeat a String N Times in Java. We had a look at different examples with the code. You can try these examples out at your local Java IDE.

Feel free to reach out for any suggestions/doubts.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *