Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tricky Java: boolean assignment in if condition

I'm trying to get prepared for the OCA Java certification and got stuck in some questions dealing assignment in if conditions. Can anyone explain me the reason of the different behaviours in the code below? By my point of view I'm just putting the same two boolean values in an "inclusive or" condition 6 times...

package pck;

 class SuperMain{
    boolean b;
    public static void main(String args[]){
        new SuperMain();
    }
    SuperMain(){
        if(_true()|_false())
            System.out.println(b); //1 - prints false
        if(b=true|_false())
            System.out.println(b); //2 - prints true
        if(_true()|(b=false))
            System.out.println(b); //3 - prints false
        if((b=true)|_false())
            System.out.println(b); //4 - prints false
        if(b=true|(b=false))
            System.out.println(b); //5 - prints true
        if((b=true)|(b=false))
            System.out.println(b); //6 - prints false
    }
    boolean _true(){return b=true;}
    boolean _false(){return b=false;}
}
like image 342
Luigi Cortese Avatar asked Jan 16 '14 23:01

Luigi Cortese


1 Answers

The difference is in precedence. | has higher precedence ("binds tighter") than =.

So this:

if(b=true|_false())

is effectively:

if (b = (true | _false()))
    ...

Likewise this:

if(b=true|(b=false))

is effectively:

if (b = (true | (b = false))

In these cases, the assignment of false to b occurs before the assignment of true to b... so b ends up being true. In every other case, the assignments occur in the opposite order.

like image 57
Jon Skeet Avatar answered Sep 21 '22 21:09

Jon Skeet