How do I Reverse An Int Array In Java?

Now in this post, we will learn How do I Reverse An Int Array In Java? As we can do so using two ways one by using the inbuild reverse() function and the other by simple for loop as getting the array elements and storing them in another array in a reverse way using indexes.

Reverse array

Different Ways to Reverse

There two ways to reverse the array lets discuss one by one.

Reversing of array is required at number of times where we need the to access the elements Like last element concatinate to another array at the start.

Means if we want to concatinateanother arry at strtinging of first array then we can simply reverse the array and concatinate. which makes it easy to concatinate.

Using In Build Function

We can use an in build function reverse() which could reverse the array

int[] a = {8, 6, 7, 5, 3, 0, 9}
ArrayUtils.reverse(int[] array)

it will reverse the array and the value will be [9, 0, 3, 5, 7, 6, 8]

Using For Loop

We can  reverse the array by using for loop though swaping the elements and by using a temporary array to store the reversed array. Here i this we use a for loop and traverse all the elements one by one from end of array and keep on storing all the elements in anther array.

This way we can simple store all the elements of one array in to another array in any of given manner either reverse of any other custom conditions .

Let’s discuss how we can reverse using for loop

int[] validData = {8, 6, 7, 5, 3, 0, 9}
for(int i = 0; i < validData.length / 2; i++)
    int temp = validData[i];
    validData[i] = validData[validData.length - i - 1];
    validData[validData.length - i - 1] = temp;

It is a way to reverse the array and the result will be same as before That will be [9, 0, 3, 5, 7, 6, 8].


Learn More about about reversing the array at: Reverse The Array

And Also Visit at JAVA TUTORIALfor leaning more about Java and to solve More Questions and problem.

Leave a Comment

%d bloggers like this: