Hi,
Originally posted by Chinmay Kant:
Can anybody explain why the o/p of the following code is 1,4. I am not getting the logic:-
public class Main {
public static void main(String args[]){
int x =0;
for(int i=0; i < 2; i++){
x +=(x += ++x);
System.out.println(x);
}
}
}
Thanks in Advance
I hope this helps:
1ST LOOP: x=0
x +=(x += ++x);
- Inside parentheses: x = x + (1+x) ===> x = 0 + 1 = 1
- Outside: x = x + parentheses ===> x = 0 + 1 = 1
- x = 1
2ND LOOP: x=1
x +=(x += ++x);
- Inside parentheses: x = x + (1+x) ===> x = 1 + 2 = 3
- Outside: x = x + parentheses ===> x = 1 + 3 = 4
- x = 4
Regards,
Alex