Arrays

Array is basically a collection of similar type of elements that have contiguous memory location. Also we can store fixed number of elements in an array. In Java if we declare one array like arr then we use arr[0], arr[1], arr[2] and ….. arr[n] to represent individual variable.

Why we use Java?
1. We can access any data in array with the help of index number.
2. We can also retrieve the data as well as sorting, searching etc. operations perform very easily.

Limitation:
We can not grow array’s size at run time due to fixed size of array. To overcome this problem, collection framework is used in Java.

Types of Array
There are two types of array in Java.

  • Single Dimensional Array
  • Multi Dimensional Array

Single Dimensional Array in Java
Declaration:
We can declare single dimensional array by multiple way like

  • dataType[] arrayName; or
  • dataType []arrayName; or
  • dataType arrayName[];

Initialization:
arrayName = new dataType[size];
Lets see an example:

public class SingleDimensionArrayTest {
	public static void main(String[] args) {
		int arr[] = { 10, 20, 30, 40, 50 };
		for (int i = 0; i < arr.length; i++) {
			System.out.println("arr[" + i + "]=>" + arr[i]);
		}
	}
}
Output:

arr[0]=>10
arr[1]=>20
arr[2]=>30
arr[3]=>40
arr[4]=>50

We can declare, instantiate and initialize array on a single line by:
int array[5] = {10,20,30,40,50}; or we can also initialize through new keyword. For example:
int array[] = new int[]{10,20,30,40,50};

Note:

  • The array elements allocated by new keyword initialized the default values as per their types like zero (for numeric types), false (for boolean) or null (for reference types).
  • Inarray, if we try to access element outside the index of the array then compiler throws the ArrayIndexOuOfBoundException array.