2 Best Ways To Reverse A String In Java

Hello everyone!! Welcome to flower brackets blog. Here we learn 2 best ways to reverse a string in java.

Also Read – Best Way To Reverse String Array In Java

In java a string can be reversed in ‘n’ number of ways. 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

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

You May Also Like