
Reverse A String In Java – Here, we have discussed the various methods to reverse a string using java. The compiler has been added so that you can execute the programs by yourself, alongside suitable examples and sample outputs. The methods are as follows:
The following program to find reverse a string has been written in Five different ways. If you do have any doubts please do let us know.
Java program to find a reverse a string – Using Static Method
- Using Array
- Using Recursion
- Using While Loop
- Using For Loop
- Using Word by Word
Some interesting facts about String and StringBuffer classes :
- Objects of String are immutable.
- String class in Java does not have reverse () method, however StringBuilder class has built in reverse() method.
- StringBuilder class do not have toCharArray() method, while String class does have toCharArray() method – For more additional info Java Online Training
Example 1:
package stringreverse;
import java.util.*;
public class Stringreverse {
public static void main(String[] args) {
// TODO code application logic here
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to reverse");
original = in.nextLine();
int length = original.length();
for (int i = length - 1 ; i >= 0 ; i--)
reverse = reverse + original.charAt(i);
System.out.println("Reverse of the string: " + reverse);
}
}
output:
Example 2: Using String Buffer:
package stringbuffer;
public class Stringbuffer {
public static void main(String[] args) {
// TODO code application logic here
StringBuffer a = new StringBuffer("Java string buffer");
System.out.println(a.reverse());
}
}
Output:

Example 3:
package whileloop;
import java.util.*;
public class Whileloop {
public static void main(String[] args) {
String str;
Scanner scan=new Scanner(System.in);
System.out.print("Enter a string : ");
str=scan.nextLine();
System.out.println("Reverse of a String '"+str+"' is :");
int i=str.length();
while(i>0)
{
System.out.print(str.charAt(i-1));
i--;
}
}
}
Output:

To get in-depth knowledge, enroll for live free demo on Java Online Course
