为什么使用赋值和等式检查的 if 语句的计算结果为 false?

当 Java如果声明具有一个赋值和一个等式检查 OR-d 时,它是如何工作的?

public static void test() {
boolean test1 = true;
if (test1 = false || test1 == false) {
System.out.println("TRUE");
} else {
System.out.println("FALSE");
}
}

为什么这个印刷是假的?

6502 次浏览

The expression is not parsed the way you think. It's not

(test1=false) || (test1 == false)

in which case the result would have been true, but

test1 = (false || test1 == false)

The value of false || test1 == false expression is computed first, and it is false, because test1 is set to true going into the computation.

The reason it is parsed this way is that the precedence of the || is lower than that of the == operator, but higher than the precedence of the assignment operator =.

This is a precedence issue, basically. You're assuming that your code is equivalent to:

if ((test1 = false) || (test1 == false))

... but it's not. It's actually equivalent to:

if (test1 = (false || test1 == false))

... which is equivalent to:

if (test1 = (false || false))

(because test1 is true to start with)

... which is equivalent to:

if (test1 = false)

which assigns the value false to test1, with the result of the expression being false.

See the Java tutorial on operators for a useful table of operator precedence.

(test1 = false || test1 == false) returns false, because both of them are false.(test1 = false || test1 == true) this is true because one of them is true

please have a look over precedence of operators

Expression test1 = false || test1 == false will evaluate in following step.

STEP:1- test1 = false || test1 == false //precedence of == is highest

STEP:2- test1 = false || false// Operator || have higher precedence

STEP:3- test1 = false

STEP:4- false

Since boolean value of expression becomes false.So else statement is being executed.