In this post, I will demonstrate how to reverse a String in Java. You can do this in the most obvious way i.e. iterating through the String in the reverse order and creating a new String. The following code snippet demonstrates this:
private static String reverse(String str) {
String reversedString = "";
for(int i = str.length()-1;i >=0 ; i--){
reversedString = reversedString + str.charAt(i);
}
return reversedString;
}
A better way is to use Java’s StringBuilder class that has an in-built reverse method. The following code snippet demonstrates this:
StringBuilder strBuilder = new StringBuilder(str);
String reversedString = strBuilder.reverse().toString();