I simply,don't understand how this code makes these result | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

I simply,don't understand how this code makes these result

int x=0; int y=0; if(++x>4&&++y>2) x++; System.out.println(x); And result is 1 How???

18th Aug 2021, 9:17 AM
Samir Krasnic
Samir Krasnic - avatar
5 Answers
+ 5
First the ++x in if loop gets incremented which makes x value set to 1 . Now after that the condition becomes false but remember that x is already incremented by 1.
18th Aug 2021, 9:20 AM
Abhay
Abhay - avatar
+ 2
but how is incremented,when condition is not true?
18th Aug 2021, 9:32 AM
Samir Krasnic
Samir Krasnic - avatar
+ 2
Samir Krasnic Abhay has given a really good answer. Could I ask you to review lesson 7.1 of the Java tutorial. The section regarding prefix & postfix of incrementation or decrementation. Your example code has an example of the effects of prefix incrementation, which means x was increased by 1 before the condition was evaluated. The condition proved to be false, so the code moves on to the next section. Since x is now 1 because of the prefix increment, the output is 1.
18th Aug 2021, 10:08 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 1
Samir Krasnic compiler starts evaluating the expression from left to right . First it sees "++x" and increments value of x by 1 . Then it sees x>4 is false . As you can see x has been incremented prior to the condition becoming false . Just because something is false doesn't implies nothing will happen .
18th Aug 2021, 9:39 AM
Abhay
Abhay - avatar
+ 1
Thanks,i thought different
18th Aug 2021, 10:22 AM
Samir Krasnic
Samir Krasnic - avatar