-1

I have a simple code below:

public class Foo {
    public static void main(String[] args) {
        boolean v = true;
        v = v || hello();
        System.out.println(v);
    }

    public static boolean hello() {
        System.out.println("inside hello");
        return true;
    }
}

and it prints:

true

But if I change the expression:

v = v || hello();

to

v |= hello();

It prints:

inside hello
true

Can anyone please explain why this is happening? I assumed that they should have identical behavior but in case of |= operator, the short-circuit is not happening.

Gurwinder Singh
  • 38,557
  • 6
  • 51
  • 76
  • 1
    Why would you assume they're the same? `v |=` is equivalent to `v = v |`. If you want short-circuiting behavior, you'll have to use the nonexistent `v ||=`. – shmosel Aug 15 '18 at 04:00
  • This is happening as per the standard short-circuit behavior. Which says if any condition in || statement becomes true then it will not check further as the result will be true only. so once it's getting v as true it's returning immediately if you set v = false then it will give the same output as second. For the second it needs to execute both statements of |= operator and apply the operator. – Shivang Agarwal Aug 15 '18 at 04:02
  • @shmosel - The expression `x |=` is what they use for booleans too. – Gurwinder Singh Aug 15 '18 at 05:11
  • How did I imply otherwise? You know `|` is also a boolean operator, right? – shmosel Aug 15 '18 at 05:20
  • @shmosel - Sun's answer is what I was looking for. Thanks for your help. – Gurwinder Singh Aug 15 '18 at 05:23

2 Answers2

2

15.26.2. Compound Assignment Operators will not cause short circuit :

First, the left-hand operand is evaluated to produce a variable. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the right-hand operand is not evaluated and no assignment occurs.

Otherwise, the value of the left-hand operand is saved and then the right-hand operand is evaluated.

...

xingbin
  • 27,410
  • 9
  • 53
  • 103
0

In Java || has a short-circuit, the right hand side will not be evaluated if the left hand side is true - because the value on the right doesn't matter in that case. So in your first example, hello() is never called.

The second example is actually using a different operator, the bitwise OR operator | which cannot do the short-circuit because it is for doing bit operations on numbers (but also works on booleans). It will work the same if you expand it out to v = v | hello().

Will Richardson
  • 7,780
  • 7
  • 42
  • 56