Reverse a String in Java

This is one of the popular java interview questions asked by many interviewers. The idea of this post is to provide some of the popular ways to reverse a String.

Below are some of the popular ways to reverse a string in java. Note that there is no reverse method in String, otherwise we could have avoided all these workaround methods.

Reverse String using StringBuilder or StringBuffer

Easiest solution to this is by using StringBuffer and StringBuilder classes which provides reverse method, so we can use that to reverse a string.


Reverse String using Char Array

Another ways is by using a char array and then traverse it in reverse direction and populate a second char array from it. Then use the second char array to create the string that will be reversed of the first one.



Reverse String using Byte Array

This is Same char array, but using byte array. Code is shown below.


Reverse String Word by Word

Sometimes we want words to be reversed in a sentence, not char by char. Below is a sample code showing how to do it using String split function and StringBuilder.




Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Notify of