OneCompiler

[Java] How to reverse elements in an array?

I want to reverse all the elements in an array, how can I do that in Java?

1 Answer

4 years ago by

We can create a List using Arrays.asList anduse Collections.reverse to reverse an array. This mutates the original array. Following code shows how to do that

import java.util.Arrays;
import java.util.Collections;

public class JavaArrays {
	public static void main(String[] args) {
		String[] colors = { "blue", "red", "green", "yellow" };
		
		Collections.reverse(Arrays.asList(colors));
		
		System.out.println(Arrays.toString(colors));
	}
}

Output:

[yellow, green, red, blue]

Try this code online here: https://onecompiler.com/java/3xmtb7xh7

4 years ago by Karthik Divi