String Reverse Java


There is no straight way to reverse a string in Java. reverse() method is not included in String class as String is immutable. We use reverse() method of StringBuffer class to reverse a string. In the following code, string palindrome is checked with string reverse.
public class Demo
{
  public static void main(String args[])
  {
    String str1 = "radar";          

    StringBuffer sb1 = new StringBuffer(str1);
    sb1.reverse();                                    // see string reverse done here
    String str2 = sb1.toString();

    if(str1.equals(str2))
    {
      System.out.println(str1 + " is palindrome");    // this prints
    }                                                                       
    else
    {
      System.out.println(str1 + " is not palindrome");  
    }
                              // all the above code can be converted into a single step using anonymous StringBuffer class.

    System.out.println(str1.equals(new StringBuffer(str1).reverse().toString()));  // prints true
  }                                                                                // String Reverse on anonymous StringBuffer object
}


String Reverse
Output screen on String Reverse Java

All the code, it looks all around process.

StringBuffer sb1 = new StringBuffer(str1);
sb1.reverse();
String str3 = sb1.toString();

As reverse() method does not exist with String class, but exists in StringBuffer class, the string str1 is passed as parameter to StringBuffer constructor. reverse() method is applied on StringBuffer object sb1. All the string stored in the sb1 gets reversed. As equals() method cannot be applied on StringBuffer object, sb1 is converted back to string using toString() method of Object class.

An experienced programmer does not go all this process. He uses a single statement as follows.

System.out.println(str1.equals(new StringBuffer(str1).reverse().toString()));

All the String and StringBuffer methods are discussed very elaborately with examples.

Leave a Comment

Your email address will not be published.