Problem: Write a Java program to reverse a string, 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.

Reverse String in Java using For Loop

  1. Input the string (str).
  2. Loop through the string from back to front (i).
  3. Concatenate each character at i of str to rev.
  4. 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


Reverse String in Java using While Loop

Output

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


In this method, we are using the same approach as the first java program but instead of for loop, we are using while loop.

The loop starts from the last index of the input string (i.e str.length()-1) and will end on 0.

Reverse String in Java Without Loop

Java has StringBuilder class has inbuilt reverse() method to reverse a string.

We have to create an instance of StringBuilder using the input string as a parameter.

Output

Enter a String
Dhoni
Reversed String: inohD


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

Leave a Reply