Let's analyze the code a bit:
int[] n = {1, 2, 5, 1, 2, 3, 4, 2, 4, 1};
declares and initializes an array of 10 positions that stores 10 integers ( int
) defined. Note that all numbers are between 0 and 6
int[] occ = new int[6];
declares and initializes an array of 6 positions, but the values are not defined. Since an int can not be null
, all positions take the default value: 0 (zero)
for (int i = 0; i < n.length; i++) { //bucle de 10 iteraciones
++occ[n[i]];
}
The complex part of the loop I am going to rewrite it like this:
int indice= n[i]; //tomamos el valor de la posición i del array n
++(occ[indice]); //equivalente a occ[indice] = occ[indice] +1;
Therefore, n is an array that stores the positions that will be incremented by 1 in the occ array.
For example, in the array n appears 1 three times, so position 1 of the array occ will be incremented 3 times. The 4 appears 2 times, so that position will be worth 2 after the loop.
System.out.println(occ[1]); // 3
System.out.println(occ[4]); // 2
You can see the operation step by step here