java-string-examplesStrings

How to reverse a String in Java

Posted On
Posted By admin

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();

 

If you like this post, please do let me know via the comments box below.  You can also connect with me via my Facebook Page or subscribe to my Youtube channel!

Related Post

leave a Comment