Array

Java Array is a collection of same type of the elements. Java array is an Object and represents fixed number of elements. That means that the size of an array cannot be changed once it is created.

When an array is created, memory is allocated depending up on the size of the array and type of the elements array is going to hold. Each individual item in an array is called an element and it must be accessed using the array index.

Array index starts from 0 and goes up to n-1 where n is the size of an array. That means that the first element of an array is located at index 0 and last element of an array is located at size – 1 index.

You can declare an array by using type of its elements and specifying the reference name like

int[] intarray;

or

int intarray[];

Please note that we do not specify the number of elements while declaring the array. Also, declaring an array will not allocate the memory to it. Once declared, you can create an array using new keyword and assign it to the reference like,

intarray = new int[10]

Or you can do both declaring and creating an array together like,

int[] intarray = new int[10];

We can also declare, create and initialize the array with elements in one statement like,

int[] intarray = new int[]{1, 2, 3};

This will create an int array with 3 elements 1, 2 and 3. Note that we cannot specify the size with initialization. The following statement can also be used to create and initialize an array.

int[] intarray = {1, 2, 3};

Once the array is created, its elements can be accessed using array index. For example,

System.out.println( intarray[0] );

will print 1. Since array index starts from 0, intarray[0] will return the first element of an array. Similarly, intarray[2] will return 3 that is the last element of an array.

Below given section shows various Java array examples in details.

Java Array Examples

Join 1000+ fellow learners! Enter your email address below: