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:
Input: Pencil Output: licneP Input: Java Program Output: margorP avaJ
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.
- Input a string.
- Loop through the string characters from back to front.
- Concatenate each character to
rev
.
- Concatenate each character to
- Output
rev
.
Here is the implementation of the steps in Java:
import java.util.Scanner;
public class Main {
public static void main(String args[]){
Scanner in =new Scanner(System.in);
String str, rev = "";
//Input String
System.out.println("Enter a String");
str = in.nextLine();
//Loop in reverse order
for(int i=str.length()-1; i>=0; i--){
rev = rev + str.charAt(i);
}
System.out.println("Reversed String: "+rev);
}
}
Note: use nextLine()
instead of next()
to read the sentence as input.
Output:
Enter a Stringpencil 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.
import java.util.Scanner;
public class ReverseString {
public static void main(String args[]){
Scanner in =new Scanner(System.in);
String str, rev = "";
//Input String
System.out.println("Enter a String");
str = in.nextLine();
//last index of string
int l = str.length()-1;
//Loop from back to front through 'str'
while(l >= 0){
rev = rev + str.charAt(l--);
}
System.out.println("Reversed String: "+rev);
}
}
Output
Enter a String Reversing a string Reversed String: gnirts a gnisreveRThe 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.
import java.util.Scanner;
public class Main {
public static void main(String args[]){
Scanner in =new Scanner(System.in);
String str, rev = "";
//Input String
System.out.println("Enter a String");
str = in.nextLine();
//create an instance of StringBuilder
//pass the input string to the contructor
StringBuilder sb = new StringBuilder(str);
//Reverse using reverse() method
rev =sb.reverse().toString();
System.out.println("Reversed String: "+rev);
}
}
Output:
Enter a String Dhoni Reversed String: inohDThe 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.