Java Arrays

Java Arrays

In this tutorial, we will learn to work with arrays in Java. We will learn to declare, initialize, and access array elements with the help of examples.

An array is a collection of similar types of data. It is a container that holds data (values) of one single type. For example, you can create an array that can hold 100 values of int type.

In Java, arrays are a fundamental construct that allows you to store and access a large number of values conventienty.


How to declare an array?

In Java, here is how we can declare an array.

dataType[] arrayName;

Let's take an example,

double[] data;

Here, data is an array that can hold values of type double.

But, how many elements can array this hold?

Good question! We have to allocate memory for the array. The memory will define the number of elements that the array can hold.

data = new Double[10];

Here, the size of the array is 10. This means it can hold 10 elements (10 double types values). The size of an array is also known as the length of an array.

Note: Once the length of the array is defined, it cannot be changed in the program.

Let's take another example:

int[] age;
age = new int[5];

Here, age is an array. It can hold 5 values of int type.

In Java, we can declare and allocate memory of an array in one single statement. For example,

int[] age = new int[5];

Java Array Index

In Java, each element in an array are associated with a number. The number is known as an array index. We can access elements of an array by using those indices. For example,

int[] age = new int[5];
Java array index
Java Array Index

Here, we have an array of length 5. In the image, we can see that each element consists of a number (array index). The array indices always start from 0.

Now, we can use the index number to access elements of the array. For example, to access the first element of the array is we can use age[0], and the second element is accessed using age[1] and so on.

Note: If the length of an array is n, the first element of the array will be arrayName[0] and the last element will be arrayName[n-1].

If we did not store any value to an array, the array will store some default value (0 for int type and false for boolean type) by itself. For example,

class ArrayExample {
    public static void main(String[] args) {
    
        // create an array of length 5  
        int[] age = new int[5];
     
        // access each element of the array using the index number 
        System.out.println(age[0]);
        System.out.println(age[1]);
        System.out.println(age[2]);
        System.out.println(age[3]);
        System.out.println(age[4]);
    }
}

Output:

0
0
0
0
0

In the above example, we have created an array named age. However, we did not assign any values to the array. Hence when we access the individual elements of the array, the default values are printed to the screen.

Here, we are individually accessing the elements of the array. There is a better way to access elements of the array using a loop (generally for-loop). For example,

class ArrayExample {
    public static void main(String[] args) {

        // create an array of length 5
        int[] age = new int[5];

        // accessing elements using for loop
        for (int i = 0; i < 5; ++i) {
            System.out.println(age[i]);
        }
    }
}

Output:

0
0
0
0
0

How to initialize arrays in Java?

In Java, we can initialize arrays during declaration or you can initialize later in the program as per your requirement.

Initialize an Array During Declaration

Here's how you can initialize an array during declaration.

int[] age = {12, 4, 5, 2, 5};

This statement creates an array named age and initializes it with the value provided in the curly brackets.

The length of the array is determined by the number of values provided inside the curly braces separated by commas. In our example, the length of age is 5.

Elements are stored in the array
Java Arrays initialization

Let's write a simple program to print elements of this array.

class ArrayExample {
    public static void main(String[] args) {

        // create an array 
        int[] age = {12, 4, 5, 2, 5};

        // access elements of tha arau
        for (int i = 0; i < 5; ++i) {
            System.out.println("Element at index " + i +": " + age[i]);
        }
    }
}

Output:

Element at index 0: 12
Element at index 1: 4
Element at index 2: 5
Element at index 3: 2
Element at index 4: 5

How to access array elements?

As discussed before, we can easily access and alter elements of an array by using its numeric index. For example,

class ArrayExample {
    public static void main(String[] args) {

        int[] age = new int[5];

        // insert 14 to third element
        age[2] = 14;

        // insert 34 to first element
        age[0] = 34;

        for (int i = 0; i < 5; ++i) {
            System.out.println("Element at index " + i +": " + age[i]);
        }
    }
}

Output:

Element at index 0: 34
Element at index 1: 0
Element at index 2: 14
Element at index 3: 0
Element at index 4: 0

Example: Java arrays

The program below computes sum and average of values stored in an array of type int.

class SumAverage {
    public static void main(String[] args) {

        int[] numbers = {2, -9, 0, 5, 12, -25, 22, 9, 8, 12};
        int sum = 0;
        Double average;
     
        // for each loop is used to access elements 
        for (int number: numbers) {
            sum += number;
        }
     
        int arrayLength = numbers.length;

        // Change sum and arrayLength to double as average is in double
        average =  ((double)sum / (double)arrayLength);

        System.out.println("Sum = " + sum);
        System.out.println("Average = " + average);
    }
}

Output:

Sum = 36
Average = 3.6

In the above example, we have created an array of named numbers. We have used the for...each loop to access each element of the array. To learn more about for...each loop, visit Java for...each loop.

Inside the loop, we are calculating the sum of each element. Notice the line,

int arrayLength = number.length;

Here, we are using the length attribute of the array to calculate the size of the array. We then calculate the average using:

average = ((double)sum / (double)arrayLength);

As you can see, we are converting the int value into double. This is called type casting in Java. To learn more about typecasting, visit Java Type Casting.

_______________________________________________________________________

Multidimensional Arrays

Arrays we have mentioned till now are called one-dimensional arrays. However, we can declare multidimensional arrays in Java.

A multidimensional array is an array of arrays. That is, each element of a multidimensional array is an array itself. For example,

double[][] matrix = {{1.2, 4.3, 4.0}, 
      {4.1, -1.1}
};

Here, we have created a multidimensional array named matrix. It is a 2-dimensional array. To learn more, visit Java multidimensional array.


Also check out these sources:

  • Java copy array
  • Java array methods
  • Java array to list and list to array
  • Java String array
  • Java int array
  • Double array Java
  • Java array of objects
  • Java String to array and array to String conversion
  • How to print arrays in Java?
  • Is it possible to have a dynamic length of an array in Java?