String Reverse Java

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.


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 Reply

Your email address will not be published. Required fields are marked *