Originally posted by nitin sharma:
public class lap
{
public static void main(String[]rgs)
{
for(int j=0,k=0;j<10&&k<10;k+=++j==10 ? 1+(j=0):0)
System.out.println( " k "+k+", j "+j);
}
}
Hi everybody,
can anybody explain that loop.?
-----------------------------
Step 0 = first part of for
step 1 = second part of for
step 2 = third part of for
for # 1: step 0: j=0 k=0
step 1: Step 1-1: j<10 gives true
Step 1-2: k<10 gives true
Step 1-3: true && true gives true
---Thus prints k=0, j=0
step 2: Now we see at k+=++j==10 ? 1+(j=0):0
Now according to JVM it this expression has to do four MAJOR operators
1) +=
2) ++
3) ==
4) ? :
According to precedence table, the order of operations will be 2,3,4,1.i.e. ++, ==, ? :, +=
So here we go
step 2-1: first ++j is evaluated thus ++j giving j = 1
step 2-2: now == is evaluated thus 1==10 gives false
step 2-3: now the turnary opearator goes, So having result of false, the right side of : gives 0
step 2-4: The 0 got from the turnary operator gives k+=0 thus making k=0
FINALLY, At the end we are having k=0 and j=1
for # 2: Step 0: Will Not execute (and now onwards, step zero is ignored in this explaination)
Step 1: 1<10 && 0<10 gives true
---Prints k=0, j=1
Step 2: 2-1: makes j=2
2-2: 2==10 gives false
2-3: gives 0
2-4: k+=0 gives k=0
FINALLY, At the end we are having k=0 and j=2
for # 3: Step 1: 2<10 && 0<10 gives true
---Prints k=0, j=2
Step 2: 2-1: makes j=3
2-2: 3==10 gives false
2-3: gives 0
2-4: k+=0 gives k=0
FINALLY, At the end we are having k=0 and j=3
*****************************************************************
Now calculate urself how for # 4,5,6,7,8,9 goes and let us evaluate for # 10
*****************************************************************
for # 10: Step 1: 9<10 && 0<10 gives true
---Prints k=0, j=9
Step 2: 2-1: makes j=10
2-2: 10==10 gives TRUE
2-3: gives true side of the turnary operator.i.e. 1+(j=0) which makes j=0 and 1+0 and thus 1
2-4: k+=1 gives k=1
FINALLY, At the end we are having k=1 and j=0
for # 11: Step 1: 0<10 && 1<10 gives true
---Prints k=1, j=0
Step 2: 2-1: makes j=1
2-2: 1==10 gives false
2-3: gives 0
2-4: k+=0 gives k=1
FINALLY, At the end we are having k=1 and j=1
***************************************************************
Let us see what happens at for # 100 and for # 101
***************************************************************
for # 100: Step 1: 9<10 && 9<10 gives true
---Prints k=9, j=9
Step 2: 2-1: makes j=10
2-2: 10==10 gives TRUE
2-3: gives true side of the turnary operator.i.e. 1+(j=0) which makes j=0 and 1+0 and thus 1
2-4: k+=1 gives k=10
FINALLY, At the end we are having k=10 and j=10
for # 101: Step 1: 10<10 && 10<10 gives false
Hence the loop exits.
FINALLY, At the end we are having k=10 and j=10
---------------------------------
Thats all! Please correct me if i am wrong at any step
Thanx
Naveed