+ 5

Why only x is incremented?

int x = 10, y = 10, z = 0; if (!(x++ > 10 && y++ > 10)){ z = x + y; System.out.println(x); System.out.println(y); } System.out.println(z); and now x = 11, y = 10, and z = 21 question is why isn't y also 11 and z = 22???

4th Apr 2017, 6:13 PM
Johann Leis
Johann Leis - avatar
2 Answers
+ 12
Good Question. This is a question,for which you will have to understand the difference between & and &&. &&- Here, First condition(condition on the left of &&) is checked first,and if it evaluates to true,it proceeds to the right hand side.In your question,left condition is false(10 is not > 10),and you used &&, hence no need to evaluate right hande side(save memory) as that is going to return false irrespective of the right condition.Hence y is not incremented. If you use & instead of &&, you will get your expected result since both the sides of & will execute. Hope that helps,if you need more explanation,message me.
4th Apr 2017, 6:40 PM
Meharban Singh
Meharban Singh - avatar
+ 6
thanks! so this is all about saving memory. but i think i have to know how a CPU works because if you look at it in assembly code it makes sense that the second statement is just loaded into the ALU for comparing and after that the value needn't to be saved. besides: This is the .class-file after you decompile it: byte x = 10; int y = 10; int z = 0; int arg15 = x + 1; if (x <= 10 || y++ <= 10) { z = arg15 + y; System.out.println(arg15); System.out.println(y); } System.out.println(z);
4th Apr 2017, 6:54 PM
Johann Leis
Johann Leis - avatar