string reverse code in java code example

Example 1: how to reverse a string in java

public class ReverseString {
    public static void main(String[] args) {
        String s1 = "neelendra";
        for(int i=s1.length()-1;i>=0;i--)
            {
                System.out.print(s1.charAt(i));
            }
    }
}

Example 2: Reverse a string in java

// reverse a string using character array
class ReverseUsingCharacterArray
{
   public static void main(String[] args)
   {
      String str = "HelloWorldJava";
      char[] ch = str.toCharArray();
      for(int a = ch.length - 1; a >= 0; a--)
         System.out.print(ch[a]);
   }
}

Example 3: 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));
   }
}