Java program to reverse an integer array

Java program to reverse an integer array

Write a Java program to reverse an integer array is one of the commonly asked Java coding interview questions for freshers.

Reversing an array is easy. All you need to do is create a new array of same size, iterate through original array from end to start and store it in the newly created array. But the interviewer may ask you to write the program without using an additional array or without using any in-built API. In such case you need to write your own implementation.

Here is a sample Java program to reverse an integer array. The program can be simply changed to reverse an array of any objects.

Java program to reverse an array without using any API

Solution:1

Below is the output of running the above program.

Solution:2

Below is the output of running the above program.

The logic of the above two solutions is simple. Swap the elements from the start with the elements from the end. In case of solution 1, two indices are used, one to hold the index from the beginning and another to hold the index from end. The swapping should be done until the indices do not cross each other. In case of solution 2, only one index is used to hold the elements from the beginning and the end index (numbers.length-1) is subtracted to the value of i to get the index of elements from the end.

You may be interested to know how to solve it using in-built API. Here is a solution.

Below is the output of running the above program.

That’s all about how to reverse array in Java.

Also read,

How to reverse an ArrayList in Java

The following two tabs change content below.
Working as a Java developer since 2010. Passionate about programming in Java. I am a part time blogger.
2 comments

Add Comment

Required fields are marked *. Your email address will not be published.