How to Reverse a String in Java


Reversing a String in java is one of the most common topic programmers come across at some point of time. And since there is more than one method to reverse a string in java, it creates confusion sometimes, as which one is supposed to be used when?

Methods to Reverse a String

  • Static Method
  • String to Character Array
  • Using StringBuilder class
  • Using reverse() function of StringBuilder class

There are some other methods too which are being followed by some programmers, but these four are the famous ones. Let us look at each method with an example.


Static Method


Output

Let us look at the output of the above example code.

Static Method
Fig.1- Static Method

In the above example code, we are reading the string passed by the user and following that we will begin an iteration loop that will build the new reversed string. For loop is responsible for obtaining the characters of the original string individually from the end using the charAt() function of the string class. After obtaining the characters from the end individually, the characters are concatenated using the “+” operator.

String to Character Array


Output

Let us look at the output of the above example code.

String to Character Array
Fig.2- String to Character Array

Here we convert the String to Character Array by using the built – in Java String class method toCharArray(). After the conversion just scan the String from end to start and the characters one by one.

Using StringBuilder class


Output

Let us look at the output of the above example code.

Using StringBuilder Class
Fig.3- Using StringBuilder Class

The only difference between this approach and that of Static method is the use of append function of the StringBuilder class in the iteration loop instead of concatenating the characters to form the reversed string.

Using reverse() function of StringBuilder Class

Output

Let us look at the output of the above example code.

Using reverse() function
Fig.4- Using reverse() function

It is the easiest approach to this problem where we have to simply use the Java StringBuilder class`s reverse() function, and that`s it, the String is reversed.

Summary

Having discussed four different approaches to reverse a string, though there are various other methods too which are being followed, it all boils down to an individual`s requirement, restrictions and whatever suits you the best, just go ahead with that, but there`s no harm in acquiring knowledge regarding various strategy.

Read More

Author : Satyam Kumar -



You will also like: