Concept of Array in Java

An array is a collection of similar data types. Array is a container object that hold values of homogenous type. It is also known as static data structure because size of an array must be specified at the time of its declaration.

An array can be either primitive or reference type. It gets memory in heap area. Index of array starts from zero to size-1.


Array Declaration

Syntax :

datatype[ ] identifier;
or
datatype identifier[ ];

Both are valid syntax for array declaration. But the former is more readable.

Example :

int[ ] arr;
char[ ] arr;
short[ ] arr;
long[ ] arr;
int[ ][ ] arr;   // two dimensional array.


Initialization of Array

new operator is used to initialize an array.

Example :

int[ ] arr = new int[10];    //10 is the size of array.
or
int[ ] arr = {10,20,30,40,50};

Accessing array element

As mention ealier array index starts from 0. To access nth element of an array. Syntax

arrayname[n-1];

Example : To access 4th element of a given array

int[ ] arr = {10,20,30,40};
System.out.println("Element at 4th place" + arr[3]);
The above code will print the 4th element of array arr on console.


foreach or enhanced for loop

J2SE 5 introduces special type of for loop called foreach loop to access elements of array. Using foreach loop you can access complete array sequentially without using index of array. Let us see an example of foreach loop.

class Test
{
public static void main(String[] args)
  {
    int[] arr = {10, 20, 30, 40};
	for(int x : arr)
	{
		System.out.println(x);
	}
   }
}

Output :

10
20
30
40