Can someone please explain what is going on in this method?
class test{
public static void main(String args[])
{
int[] x = new int[4];
int[] xy = new i
For Each loop that you have used in here does assign j a value that is already assigned to array x (which in your case is 0 ).
As according to your case of x and xy array:-
x[0]=0; xy[0]=0
x[1]=0; xy[0]=0
x[2]=0; xy[0]=0
x[3]=0; xy[0]=0
Describing for each loop according to your program case:-
for(j : x)
This implies it will run for 4 times which is the length of your array x.
when running first time the following process will happen
j=x[0] (so j=0 coz x[0] according to your case)
xy[0]=xy[0]+1 (so now xy[0] value becomes 1)
Similarly for the second run of for each
j=x[1] (so j=0 coz x[0] according to your case)
xy[0]=xy[0]+1 (so now xy[0] value becomes 2 as in previous for each run xy[0]=1)
So all in all finally you will have xy[0]=4
at the end of 4th run of for each loop.
Finally the print statement will print 4.
It should be straight-forward to find out, if you trace through using debugger.
In brief, it is getting each value in x
, and use the value as index to increment corresponding value in xy
.
It will be more obvious if you initialize both array with meaningful values:
int[] x = {1,1,3,3}
int[] xy = new int[4]; // initialized to 0 by default
after your piece of code, you will find xy
containing {0,2,0,2}
.
You should understand how enhanced-for-loop is expanded for array:
for (T v : arr) {
// do something
}
is transformed to
for (int i = 0; i < arr.length; ++i) {
T v = arr[i];
// do something
}
Obviously your understanding on how enhanced for loop being expanded is wrong.
In your case you need only for-loop and not enhanced for-loop:
for(int j = 0 ; x.length > j; j ++) {
xy[j] += 1;
}
Problem with your code is that your loop traverse only at index 0 of xy hence you get xy as [4, 0, 0, 0]
int[] x = new int[4];//default values [0, 0, 0, 0]
int[] xy = new int[4]; //default values [0, 0, 0, 0]
for(int j : x) { // j is always 0
xy[j] += 1;// xy[0] += 1
}
Here in the advanced for loop, the int j does not represent the index. Rather it represents the values in the xy[] array. It is not possible to get the index of advanced for loop. If you want index, then you might have to use ordinary for loop. Ex. If you have
xy[]={5,8,3,4};
for(int j:xy)
{
println(j);
}
then the output would be
5
8
3
4
int[] x = new int[4];
This creates an array of 4 elements. Each element's value is 0.
for(int j : x) {
xy[j] += 1;
}
This iterates through all the values of x
. At each iteration, j
is the next element in x
, but since all elements are initialized to 0, j is always 0. So, the 4 iterations increment xy[0]
.
You can use the for-loop instead:
for(int i = 0 ; x.length > i; i ++) {
xy[i] += 1;
}
If you want to still use for each then here is the example
a[]={1,2,3,4};
for(int i:a)
{
println(i);
}
Hope it helps!