Java String reverse with and without reverse() Example


To reverse a string with less code in Java, there comes reverse() method in StringBuffer class. reverse() method cannot be used directly on string as reverse() is not defined in String class but defined in StringBuffer and StringBuilder. String should be converted to StringBuffer and then applied reverse() method.

1. Reversing using reverse() method.

public class StringMethodDemo
{
 public static void main(String args[])
 {
  String str1 = "ABCEDF"; 
  StringBuffer sb1 = new StringBuffer(str1);
  
  System.out.println("String before reversing: " + sb1);
  sb1.reverse();
  System.out.println("String after reversing: " + sb1);
   		                                       // all in one line
  System.out.println("All in one line: " + new StringBuffer(str1).reverse());
 }
}


string reverse
Output screenshot of string reverse Example

If string is required in coding after reversing, convert sb1 to string using either valueOf() method or toString() method as follows.

String str2 = sb1.toString();

2. Reversing without using string reverse method.
public class StringMethodDemo
{
 public static void main(String args[])
 {
  String originalString = "ABCEDF";
  String temp = "";
     
  int length = originalString.length();
 
  for (int i = length - 1; i >= 0; i--)
  {
   temp = temp + originalString .charAt(i);
  }

  System.out.println("String before reversing: " + originalString);
  System.out.println("String after reversing: " + temp);
 }
}


string reverse
Output screenshot of string reverse Example

Leave a Comment

Your email address will not be published.