Array is a referenced type of data type in java, it is used to create fixed number of multiple variables of same type to store multiple values of similar type in contiguous memory locations with single variable name. In java following are the important points in java:
In java array is used to collect similar type of values or objects to send all those multiple values with single call from one method to another methods either as an argument or as a return value.
Array size is fixed, means we cannot increase or decrease its size after its creation.
Ex: int arr[]=new int[5];
class ArrayDemoc { public static void main (String[] args) { // declares an Array of integers. int[] arr; // allocating memory for 5 integers. arr = new int[5]; // initialize the elements of the array arr[0] = 10; arr[1] = 20; arr[2] = 30; arr[3] = 40; arr[4] = 50; // accessing the elements for (int i = 0; i < arr.length; i++) System.out.println("Element at index " + i + " : "+ arr[i]); } }O/P
Element at index 0 : 10 Element at index 1 : 20 Element at index 2 : 30 Element at index 3 : 40 Element at index 4 : 50
Ex: int arr[][]=new int[5][5];
class MultiArrayDemo { public static void main(String args[]) { // declaring and initializing 2D array int arr[][] = { {1,2,3},{4,6,5},{8,5,6} }; // printing 2D array for (int i=0; i< 3 ; i++) { for (int j=0; j < 3 ; j++){ System.out.print(arr[i][j] + " "); } System.out.println(); } } }O/P
1 2 3 4 6 5 8 5 6