Page Contents
There are many ways to reverse String in Java. We can reverse a String using factory inbuilt method, loop iteration etc.
Program to Reverse a String using loop
class ReverseString {
public static void main(String args[]) {
String main = "proedu";
String rev = "";
int length = main.length();
for (int i = length - 1; i >= 0; i--){
rev = rev + main.charAt(i);
}
System.out.println("Reverse of the string is : " + rev);
}
}
Output
Reverse of the string: udeorp
Program to Reverse a String using Factory inbuilt method
Using StringBuffer().reverse() method
class ReverseString {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("proedu");
System.out.println("Reverse of the string is :" + sb.reverse());
}
}
Output
Reverse of the string is :udeorp
Using StringBuilder.reverse() method
class ReverseString {
public static void main(String args[]) {
StringBuilder sb = new StringBuilder("proedu");
System.out.println("Reverse of the string is :" + sb.reverse());
}
}
Output
Reverse of the string is :udeorp
Program to Reverse a String using Recursion
class ReverseString {
public static String reverse(String originalStr) {
if (originalStr.length() == 0){
return " ";
}
return originalStr.charAt(originalStr.length() - 1) + reverse(originalStr.substring(0, originalStr.length() - 1));
}
public static void main(String[] args) {
String strValue = "proedu java";
System.out.println("Reverse of the string is :: " + reverse(strValue));
}
}
Output
Reverse of the string is :: avaj udeorp