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;}
}
                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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With