Java Arrays



In this tutorial, we will learn how to work with arrays. We will see how to declare, initialize, and access array items with the help of examples.


Java Arrays

In Java, an array is a collection of similar types of data.

Arrays are used to hold multiple values in a single variable instead of using separate variables for each value.

For example, if we want to store the names of 20 companies, we can create an array of String type that can hold 20 names.

String[] companies = new String[20];

Here above, the created array cannot store more than 20 company names. The number of values in the Java array is fixed when allocating memory.


How to declare an array in Java?

The syntax of declaring an array can be given as follows:

dataType[] arrayName; 

Here,

  • dataType - it is the data type that can be primitive data types like ìnt, char, double, etc. or Java objects.
  • arrayName - it is the given identifier.

For example,

int[] myNum; 

Here, myNum is an array that can hold values of type int.

How many items can this array hold?

To define the number of items that an array can hold, we need to allocate the memory of that array. For example,

// declare an array 
int[] myNum;

// allocate memory
myNum = new int[20];

Above, the array can hold 20 items. So the size or the length of the array is also 20.

We can declare and allocate the memory of an array in one single statement. For example,

int[] myNum = new int[20];

How to initialize Arrays in Java?

In Java, we can initialize arrays during declaration.

Let us see the following example,

// declare and initialize an array
int[] myNum = {27, 11, 7, 9, 35};

Here above, we have created an array named myNum and initialized it with values inside the curly brackets.

In the example above, we have not provided a size for the array. So, the Java compiler automatically defines the size by counting the number of items in the array.

In a Java array, each memory location is associated with an array index. So we can also initialize arrays using the index number. For example,

// declare an array
int[] myNum = {27, 11, 7, 9, 35};

// initialize the array
myNum[0] = 27;
myNum[1] = 11;
myNum[2] = 7;
myNum[3] = 9;
myNum[4] = 35;
Array Indexing in Java

Note:

  • In Java, array indices always start from 0, which is the first item of the array.
  • If the size of an array is n, then the last item of the array will be at index n-1.

How to Access Items of an Array in Java?

To access items of an array, we can use the index number.

The syntax for accessing items of an array can be given as follows:

array[index]

Example: Access Array Items

In the following example, we will see how to access array items using index numbers.

public class Main {
    public static void main(String[] args) {
        
        // create an array
        String[] fruits = {"apple", "kiwi", "mango", "apricot"};

        // access each array items
        System.out.println("Accessing Items of Array: ");
        System.out.println("First item: " + fruits[0]);
        System.out.println("First item: " + fruits[1]);
        System.out.println("First item: " + fruits[2]);
        System.out.println("First item: " + fruits[3]);
    }
}

Output

Accessing Items of Array: 
First item: apple
First item: kiwi
First item: mango
First item: apricot

As we can see above, we used the index number to access each item of the array.

We can also use loops to access all the items of the array at once.


Looping Through Array Items

In Java, we can use loops to loop through each item of an array.

Let us see some examples.


Example: Using for Loop

In the following example, we will use the for loop to display each item of an array.

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

        // create an array
        String[] fruits = {"apple", "kiwi", "mango", "apricot"};

        // loop through the array
        System.out.println("Using for loop:");
        for(int i = 0; i < fruits.length; i++) {
            System.out.println(fruits[i]);
        }
    }
}

Output

Using for loop:
apple
kiwi
mango
apricot

As we can see above, we have used the length property of the array to get its size.

Example: Using the for-each Loop

In the following example, we will use the for-each loop to display each item of an array.

public class Main {
    public static void main(String[] args) {
        
        // create an array
        String[] fruits = {"apple", "kiwi", "mango", "apricot"};

        // loop through the array
        System.out.println("Using for-each Loop: ");
        for(String fruit : fruits){
            System.out.println(fruit);
        }
    }
}

Output

Using for-each Loop: 
apple
kiwi
mango
apricot

Example: Calculate the Sum And Average of Array Items

In the following example, we will compute the Sum and Average of an array of elements.

public class Main {
    public static void main(String[] args) {
        
        int[] numbs = {4, 6, 17, 23, 11, 31, 2, 12};
        int sum = 0;
        Double average;

        // calculating the Sum of items using for-each loop
        for(int numb: numbs) {
            sum += numb;
        }

        // get the total number of items
        int size = numbs.length;

        // calculate the average 
        average = ((double)sum / (double)size);

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

Output

Sum = 106
Average = 13.25

Notice the line,

int size = numbs.length;

Here, we have used the length attribute of the array to get the size of the array that we will use to calculate the average.

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

Here, we converted the int value into double. This is called type casting in Java.


Multidimensional Arrays

Until now, we have used one-dimensional arrays. But, we can also declare multidimensional arrays in Java.

A multidimensional array is an array of arrays. This means that each item of a multidimensional array is an array itself. For example,

int[][] multi = { {1, 2, 3}, {4, 5}, {6, 7, 8, 9}};

Here, we have created a multidimensional array named multi. It is a 2-dimensional array.



ExpectoCode is optimized for learning. Tutorials and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using this site, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 2020-2021 by ExpectoCode. All Rights Reserved.