You are currently viewing Arrays and Loops in Java

Arrays and Loops in Java

1. Introduction

An array is a data structure that holds a fixed number of items of a single type. In this article, you will learn how to create and manipulate an array in Java. We will not cover multidimensional arrays in this article.

2. Declaring an Array

You may declare a variable of type array in any of the following ways:

type[] myArrayVariable;

Or

type myArrayVariable[];

type can be any of the primitive types as well as a Java object.

Below are some valid array declarations:

        int[] myIntArray;
        int myOtherIntArray[]; //valid but not commonly used
        String[] arrayOfStrings;
        Person[] myObjectArray;

3. Initializing an Array

Declaring an array does not make it usable. The following code will not compile:

        int[] myIntArray ;
        System.out.println(myIntArray[0]);//Array is not initialized

Just like any other object in Java, You must initialize an array before using it. There are two ways of achieving this.

3.1. Initialize with size

Use the [] operator and provide the size of your array in this way:

        int[] myIntArray = new int[5];

In the above code, we are creating an array of 5 integers. Arrays in Java are zero-indexed. The first value of the array is at index 0 and the last value is at index “Array size – 1“. This means that the values in the above array are myIntArray[0], myIntArray[1], myIntArray[2], myIntArray[3], and myIntArray[4].

You MUST provide the size of your array during initialization. The following code fails to compile due to missing size:

    int[] myOtherIntArray = new int[]; //Does not compile. Array size is missing

3.2. Initialize with values

You may also initialize an array by providing an initial value.

        int[] anIntArray = {1,2,3,4,5};

Java implicitly determines the array size, which is 5 here.

This way of initializing an array will not work if you separate the array declaration and the initialization. The following code will not compile:

        int[] myIntArray ;
        myIntArray = {1,2,3,4,5}; // Does not compile. Cannot separate the declaration and the initialization in this context.

This is because the array initializer is not a valid Java expression. To overcome this, you must combine the new operator and the initializer in this way:

        int[] anotherIntArray = new int[]{1,2,3,4,5};

4. Accessing an Array

An array is a fixed-size collection of items. To access an item in the array, you must use its index and the [] operator in this way:

type myVariable = myArray[index]

Where type is the data type of the items in the array.

        int[] anIntArray = {1,2,3,4,5};
        int anInt = anIntArray[0];//1
        int anotherInt = anIntArray[4];//5
        System.out.println(anIntArray[2]);// prints 3

5. Miscellaneous operations on an Array

5.1. Accessing the size

Access the length attribute of the array to obtain its size.

        int[] anIntArray = {1,2,3,4,5,6,7,8,9,10};
        int size = anIntArray.length; //10

5.2. Looping through an array

Depending on your needs, you may use a simple for loop, an enhanced for loop, or a while loop.
Simple for loop

        for(int i=0; i< anIntArray.length; i++){
            System.out.println(anIntArray[i]);
        }

Enhanced for loop

        for(int value : anIntArray){
            System.out.println(value);
        }

While loop

        int i=0;
        while(i < anIntArray.length){
            System.out.println(anIntArray[i]);
            i++;
        }

5.3. Displaying the content of an Array

The default toString() method on an array will simply print the memory address of the array.

        int[] anIntArray = {1,2,3,4,5,6,7,8,9,10};
        System.out.println(anIntArray);//[I@6acbcfc0

To display the content of an array, you can loop through the items and display them individually(see previous section). Alternatively, you can use the Arrays utility class.

6. Conclusion

In this article, you learned the fundamental aspects of the array type in Java.
You can find the complete code of this article here in GitHub.

Noel Kamphoa

Experienced software engineer with expertise in Telecom, Payroll, and Banking. Now Senior Software Engineer at Societe Generale Paris.

This Post Has One Comment

Leave a Reply