Boolean expressions in Java

后端 未结 8 1188
不知归路
不知归路 2020-12-21 06:00

I have a question about the meaning (evaluation) of Boolean variables in return statements in Java.

I know that:

if (var) { ... }

i

8条回答
  •  情歌与酒
    2020-12-21 06:28

    Yes, this is true for all booleans. You can think of if(expression) evaluating 'expression' to see if it's 'true' or 'false'. When you do

    if(b < a == true)
    

    it first tests to see if b < a and if it is, it now tests:

    if(true == true)
    

    It now tests whether true == true (which it obviously does). Java isn't doing anything tricky when you leave out the extra '== true', it just needs to perform one fewer test. There's no reason you couldn't say:

    if(((b < a == true) == true) == true)
    

    but it would cause Java to perform an extra test each time it sees an equals sign.

提交回复
热议问题