简体   繁体   中英

Is it possible in an “if-statement” to execute the actual statement if the condition is false?

I encountered the code example below in the JavaNotes book. The answer was that after execution the x is equal to 2.

My question is how exactly does this work?

I see it is not an if-else flow, but in the second "if" the boolean expression is false, so X shall not obtain value 2. How is this happening?

int x; 
x = -1; 
if (x < 0) 
  x = 1;
if (x >= 0) 
  x = 2;

Try rubber duck debugging ! Read the comment in the code so you can understand how your code work :

int x;
x = -1;
if (x < 0) { //-1 < 0 = true
    x = 1;   //enter here -> change x = 1
}//end of the first if

if (x >= 0) {//1 >= 0 = true
    x = 2;   //enter here -> change x = 2
}//end of the second if

System.out.println(x);//result is 2

If you expect x = 1 then your code should look like this :

if (x < 0) { //-1 < 0
    x = 1;   //enter here -> change x = 1
} else if (x >= 0) {//1 >= 0
//^^^^------------------------------------------note the else
    x = 2;   //enter here -> change x = 2
}

x = -1; first if: x < 0 is true, so x gets new value 1

second if: x > 0 is true so x gets new value 2 x = 2;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM