Arrays
We use arrays to store many objects of one type. We create them using this pattern: "type of variables that will be stored in this array - name = 'new' - the same type as before - size;" (int[] a = new int[5];
). An array index is the position number used to access or reference a specific element within an array, starting from 0. When we create an array, an appropriate amount of memory "in a row" is reserved (the amount required for a given data type times the size), but the values that were there don't vanish. We can assign all the values at declaration: int[] a = {1, 2};
. An array cannot contain elements that have different data types.
int[] a = new int[4];
a[0] = 1;
a[1] = 2;
a[2] = 3;
a[3] = 4;
for (int i: a) // iterating over an array (accessing every single array element independently) using enhanced for (where to save the values : from where to read the values)
System.out.println(i);
We can create multidimensional arrays (an array in an array, etc.) A two-dimensional array is called a matrix. To access an element from the internal array, we do as in the example below. The first index means which array we are entering, and the second index means which element of the internal array we want to access.
int[] a = new int[4]; // container for 4 variables
int[][] a1 = new int[4][3]; // 4 containers (0, 1, 2, 3) that can store 3 variables (0, 1, 2). Overall, it can store 4*3 = 12 variables.
a1[0][1] = 5;
System.out.println(a1[0][1]);
int[][][] a2 = new int[2][3][2]; // 2 containers that can store 3 other containers, which can store 2 variables. Overall, it can store 2*3*2 = 12 variables.
a2[1][2][1] = 6;
System.out.println(a2[1][2][1]);
// Defining the array's elements in a loop
int[] a = new int[100];
for (int i = 0; i < 100; i++) {
a[i] = i;
System.out.println("a[" + i + "] = " + a[i]);
}
System.out.println(a.length); // array's size (length)