Summary: In this programming example, we will learn different ways to reverse a given string in Java, given that the string could be a single word or a sentence.

Example:

We can reverse a string in Java in multiple ways. Let’s discuss each of the methods in detail.

Method 1: Using For Loop

The idea is to add each character to a new string from a given string in reverse order.

  1. Input a string.
  2. Loop through the string characters from back to front.
    1. Concatenate each character to rev.
  3. Output rev.

Here is the implementation of the steps in Java:

Note: use nextLine() instead of next() to read the sentence as input.

Output:

Enter a String
pencil programmer
Reversed String: remmargorp licnep


Method 2: Using While Loop

This method is similar to what we have done before using the ‘for’ loop. The only difference is that we are iterating in reverse order using the ‘while’ loop.

Output

Enter a String
Reversing a string
Reversed String: gnirts a gnisreveR


The loop starts from the last index of the input string (i.e., str.length()-1) and ends at 0.

Method 3: Using StringBuilder.reverse()

Java StringBuilder class has an inbuilt reverse() method that returns the reverse form of the string object.

To use this method, we have to create an instance of StringBuilder using the input string as a parameter.

Output:

Enter a String
Dhoni
Reversed String: inohD


The value returned by the reverse() method is of StringBuilder type, so we typecast it into a string using the toString() method.

In this tutorial, we learned to reverse a string in Java using loop and without using loop.

Leave a Reply