Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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

public static void test() {

    boolean test1 = true; 
    if (test1 = false || test1 == false) {
        System.out.println("Yes");
    } else {
        System.out.println("No");
    }       
}

Why is this printing No?

like image 749
dhaval joshi Avatar asked Oct 11 '16 07:10

dhaval joshi


1 Answers

Because of operator precedence. It is equivalent to this:

boolean test1 = true; 
if (test1 = (false || test1 == false)) {
...
}

The part in brackets evaluates to false.

like image 72
Axel Avatar answered Nov 14 '22 16:11

Axel