reverse string array java 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: java string reverse

String rev = new StringBuilder("Your String").reverse().toString();

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));
   }
}

Example 4: reverse string array java

//java program to reverse array using for loop
public class ReverseArrayDemo 
{
   public static void main(String[] args) 
   {
      int[] arrNumbers = new int[]{2, 4, 6, 8, 10};  
      System.out.println("Given array: ");  
      for(int a = 0; a < arrNumbers.length; a++)
      {
         System.out.print(arrNumbers[a] + " ");
      }
      System.out.println("Reverse array: ");
      // looping array in reverse order
      for(int a = arrNumbers.length - 1; a >= 0; a--) 
      {  
         System.out.print(arrNumbers[a] + " ");  
      }
   }
}

Example 5: reverse string array java

import java.util.Arrays;
public class ReverseStringArrayInJava
{
   public static void main(String[] args)
   {
      String[] strHierarchy = new String[]{"Junior Developer","Senior Developer","Team Lead","Project Manager","Senior Manager","CEO"};
      System.out.println("Given string array: " + Arrays.toString(strHierarchy));
      for(int a = 0; a < strHierarchy.length / 2; a++)
      {
         String strTemp = strHierarchy[a];
         strHierarchy[a] = strHierarchy[strHierarchy.length - a - 1];
         strHierarchy[strHierarchy.length - a - 1] = strTemp;
      }
      System.out.println("Reversed string array: ");
      for(int a = 0; a < strHierarchy.length; a++)
      {
         System.out.println(strHierarchy[a]);
      }
   }
}

Tags:

Cpp Example