Arrays and enhanced for loops?

后端 未结 6 561
闹比i
闹比i 2021-01-22 15:19

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         


        
6条回答
  •  野性不改
    2021-01-22 15:25

    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)
    
    1. This implies it will run for 4 times which is the length of your array x.

    2. 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)
      
    3. 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)
      
    4. 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.

提交回复
热议问题