How to Reverse an Array in Java?

Use a two-pointer approach with one pointer at the start and one at the end

Swap the elements at the two pointers

Move the start pointer forward and the end pointer backward

Repeat until the pointers meet or cross

Example:

`int[] arr = {1, 2, 3, 4, 5};`

`for (int i = 0, j = arr.length – 1; i < j; i++, j--) {`

` int temp = arr[i];`

` arr[i] = arr[j];`

` arr[j] = temp;`

`}`

Use `Collections.reverse()` for a `List`

Example:

`List list = Arrays.asList(1, 2, 3, 4, 5);`

`Collections.reverse(list);`

Use `Arrays.sort()` only if reversing a sorted order is not required

Use a temporary array if you want to create a reversed copy instead of modifying the original

Example:

`int[] reversed = new int[arr.length];`

`for (int i = 0; i < arr.length; i++) {`

` reversed[i] = arr[arr.length – 1 – i];`

`}`

Suggested for You

Trending Today