Java reverse string array code example

Example 1: reverse array in java

int length = array.length;
		for(int i=0;i<length/2;i++) {
			int swap = array[i];
			array[i] = array[length-i-1];
			array[length-i-1] = swap;
		}
or
Collections.reverse(Arrays.asList(array));

Example 2: 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 3: 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 4: reverse string java

String string="whatever";
String reverse = new StringBuffer(string).reverse().toString();
System.out.println(reverse);

Example 5: Java reverse string array

// reverse string array in java using collections
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ReverseStringArrayUsingCollections
{
   public static void main(String[] args)
   {
      // creating list of strings
      List<String> li = new ArrayList<String>();
      li.add("java");
      li.add("core");
      li.add("world");
      li.add("hello");
      System.out.println("Given list: " + li);
      Collections.reverse(li);
      System.out.println("After using collections: " + li);
   }
}

Example 6: 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] + " ");  
      }
   }
}

Tags:

Java Example