reverse string in java logic code example

Example 1: reverse string java

// Use StringBuilder for non-thread environment, it is faster
String string="whatever";
String reverse = new StringBuilder(string).reverse().toString();
System.out.println(reverse);

Example 2: Reverse a string in java

// reverse a string using ByteArray
class ReverseStringByteArray
{
   public static void main(String[] args)
   {
      String input = "HelloWorld";
      // getBytes() method to convert string into bytes[].
      byte[] strByteArray = input.getBytes();
      byte[] output = new byte[strByteArray.length];
      // store output in reverse order
      for(int a = 0; a < strByteArray.length; a++)
         output[a] = strByteArray[strByteArray.length - a - 1];
      System.out.println(new String(output));
   }
}

Tags:

Java Example