Hey there!
Welcome to ClearUrDoubt.com.
In this post, we will look at a Core Java program to reverse an array of elements.
Let’s take an integer array and try to reverse it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
package com.clearurdoubt; import java.util.Arrays; public class ReverseArray { public static void main(String[] args) { int[] ints = new int[] {1,2,3,4,5,6,7,8,9,10}; System.out.println("Before reversing the Array: "); System.out.println(Arrays.toString(ints)); ints = reverse(ints); System.out.println(); System.out.println("After reversing the Array: "); System.out.println(Arrays.toString(ints)); } /** * Method to reverse the elements of an array * @param input is an array of integers * @return the reversed array. */ public static int[] reverse(int[] input) { int forwardIndex = 0, backwardIndex = input.length - 1; while(forwardIndex < backwardIndex) { int temp = input[forwardIndex]; input[forwardIndex++] = input[backwardIndex]; // increment the forwardIndex input[backwardIndex--] = temp; // decrement the backwardIndex } return input; } } |
Output:
Happy Learning :).
Please leave a reply in case of any queries.