2 Best Ways To Reverse A String In Java

Sharing is healthy !!

In java a string can be reversed in ‘n’ number of ways. Here we learn 2 best ways to reverse a string in java.

Below two examples are the simplest way of reversing a string. Lets see its code implementation,

example: 2 Best Ways To Reverse A String In Java

Also Read – Best Way To Reverse String Array In Java

public class ReverseString
{
   public static void main(String[] args)
   {
      String strReverse = "Flower Brackets";
      System.out.println("Before reverse - " + strReverse);
      strReverse = new StringBuffer(strReverse).reverse().toString();
      System.out.println("After reverse - " + strReverse);
   }
}

Output:

2 Best Ways To Reverse A String In Java


Now using StringBuilder class,

example: 2 Best Ways To Reverse A String In Java

Also Read – String Compare Java Program

public class ReverseString
{
   public static void main(String[] args)
   {
      String strInput = "Flower Brackets";
      StringBuilder sb = new StringBuilder();
      sb.append(strInput);
      sb = sb.reverse();
 
      for(int x = 0; x < sb.length(); x++)
      {
         System.out.println(sb.charAt(x));
      }
   }
}

Output:

stekcarB rewolF

Sharing is healthy !!