Java supports Single-Dimensional and Multi-Dimensional arrays. In Java we have to first create an array type reference variable and then we instantiate the array using the new keyword. For example,
//First we create an array type reference variable.
int[] arr;
//Now we create an actual array with a length of 10 elements.
arr = new int[10];
It is very important to understand that arrays use indices to store values and the first index starts from 0. This means that if we have an array of length 10, as we have taken an array of 10 element above, the first element will be stored on the index number 0 and the second element will be stored on the index number 1 and the third element will be stored on the index number 2 and so on. When we declare an array we don't tell the index numbers, instead we tell the length of elements that the array will be storing. An example in given here,
//Array indices.
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
arr[5] = 60;
arr[6] = 70;
arr[7] = 80;
arr[8] = 90;
arr[9] = 100;
Java processes both Single-Dimensional and Multi-Dimensional array in the same manner. When we talk about Multi-Dimensional array, we are talking about rows and columns. Multi-Dimensional array provide us a way of storing data in row-column pattern. Declaring Multi-Dimensional array is as simple as Single-Dimensional array, we just add sets of square braces "[]" as our need. For example, if we need to declare an array with two dimensions, we use "[][]" two sets and if we need to declare an array of three-dimensions we will use "[][][]" three sets of square braces.
// Two-Dimensional array
int[][] arrT;
arrT = new int[2][2];
//Assigning values to the array
arrT[0, 0] = 11;
arrT[0, 1] = 22;
arrT[1, 0] = 33;
arrT[1, 1] = 44;
Subscribe to:
Posts (Atom)
