Different ways to reverse String in java
There can be different ways to reverse the String. Here , we are mentioning few.
Let’s understand them with example.
1. We can reverse the string by using a for loop and method charAt.
String OriginalString = "Hello World!!"; String temp = ""; System.out.println("Original String is "+OriginalString); for(int i=0;i<OriginalString.length();i++){ char ch = OriginalString.charAt(i); temp = ch +temp; } System.out.println("Reversed string is "+temp);
Output:
Original String is Hello World!!
Reversed string is !!dlroW olleH
Original String is Hello World!!
Reversed string is !!dlroW olleH
2. Using the StringBuffer class.
public class StringReverse { public static void main(String[] args) throws InterruptedException { String OriginalString = "Hello World!!"; String temp = ""; System.out.println("Original String is "+OriginalString); StringBuffer strBfr = new StringBuffer(OriginalString); strBfr.reverse(); System.out.println("Reversed string is "+strBfr); } }
Output:
Original String is Hello World!!
Reversed string is !!dlroW olleH
Original String is Hello World!!
Reversed string is !!dlroW olleH
3. Using the StringBuilder class.
public class StringReverse { public static void main(String[] args) throws InterruptedException { String OriginalString = "Hello World!!"; String temp = ""; System.out.println("Original String is "+OriginalString); StringBuilder strBld = new StringBuilder(OriginalString); strBld.reverse(); System.out.println("Reversed string is "+strBld); } }
Output:
Original String is Hello World!!
Reversed string is !!dlroW olleH
Original String is Hello World!!
Reversed string is !!dlroW olleH
Ask Question
Have any question or suggestion for us?Please feel free to post in Q&A Forum