Java Arrays

What is an Array?

An array is a way to hold more than one value at a time. It's like a list of items, it can hold primitive and non-primitive both.

The positions in an array start at 0 (zero) and go up sequentially. Each position in the array can then hold a value.

To set up an array we need to tell Java that what kind of data is going in to an array (integers, strings, boolean values, objects etc). Then need to specify a size of an Array. Please keep in mind that Arrays are static, their size is fixed and do not grow. In order to have a dynamic data collection we use Java Collections like List, Set or Map in Java.

int[ ] aryNums = new int[6];

In the above example int represents the data type, square bracket [ ]  represents that it is an array, aryNums is a name of an array and [ 6 ] represents the total size of an array.

Java will assign default values for the array. Because we've set up an integer array, the default values for all 6 positions will be zero ( 0 ).

If we want to assign a value of 14 to array position 1, the code would be this:

aryNums[1] = 14;

And to assign a value of 36 to array position 2, it is:

aryNums[2] = 36;

Don't forget, because arrays start at 0, the third position in an array has the index number 2.

If we know what values are going to be in the array, you can set them up like this instead:

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

The method of setting up an array uses curly brackets after the equals sign. In between the curly brackets, we type out the values that the array will hold. The first value will then be position 0, the second value position 1, and so on. Note that you still need the square brackets after int, but not the new keyword, or the repetition of the data type and square brackets. But this is just for data types of int values, string, and char values. Otherwise, you need the new keyword.

Example:

public class MainClass

    public static void main(String args[])

    {

        System.out.println("Array Test !");

        //step1 : first create array of 10 elements that holds object Emp.

        Emp[] employees = new Emp[10];

        //step2 : now create objects in a loop.

        for(int i=0; i<employees.length; i++){

            employees[i] = new Emp(i+1);//this will call constructor.

        }

    }

}

 

class Emp{

    int empNo;

    public Emp(int no){

        this.empNo = no;

        System.out.println("Emp constructor called and empNo is : "+empNo);

    }

}