Site icon TestingDocs.com

Write a program to reverse an array in Java?

Introduction

In this tutorial, we will write a Java program to reverse an array. Before writing the program to reverse the array, we look into some basics of an array.

Some basics

Array is used for storing groups of variables. An array is a group of variables that share the same name and are ordered sequentially. The index of array to point the variables start from zero to one less than the number of variables in the array. The number of elements that can be stored in an array is called the array’s dimension.

The key steps involved using arrays are: creating an array, declaring it, allocating it and initializing it.An array must have a specific type. Only variables of the appropriate type can be stored in an array. For example, integer type array can hold only integer values.

Java Program

Java has several shorthand for declaring, allocating and storing values in arrays. You can declare, allocate, and initialize an array at the same time and provide a list of initial values to it.

int[] a = new int[5];

or

int a[] = {11, 22, 33, 44, 55};

In the sample program we will take an integer array whose dimension is 5; i.e. the type of the array is int and the array has dimension 5. Also, a.length equals 5

Reverse an array

public class ReverseAnArray {
    public static void main(String[] args) {
        int a[] = {11, 22, 33, 44, 55};
        int array_length = a.length;
        int start = 0, end = array_length - 1;
        System.out.println("Initial Array:");
        printArray(a);
        while (start <= end) {
            int temp = a[start];
            a[start] = a[end];
            a[end] = temp;
            start++;
            end--;
        }
        System.out.println("Reversed Array:");
        printArray(a);

    }

    private static void printArray(int[] a){
        for (int anA : a) {
            System.out.print("[ " + anA + " ]");
        }
        System.out.println( "");
    }
}

 

Run output of the program:

 

Java Tutorial on this website: https://www.testingdocs.com/java-tutorial/

For more information on Java, visit the official website :

https://www.oracle.com/in/java/

Exit mobile version