Why does this if statement, with an assignment and equality check, evaluate to false?

How does a Java if statement work when it has an assignment and an equality check OR-d together??

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

Why is this printing FALSE?

Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow