-1
public class j68 {
    public static void main(String args[]){
        System.out.print(1==2||true);
    }
}


public class j68 {
    public static void main(String args[]){
        System.out.print(1==2|true);
    }
}

Both of above print true.Does it mean that we can use | instead of || ?

1 Answers1

0

Yes and no, but mostly no, for a couple of reasons.

There's a big difference between | (bitwise) and || (logical): With a bitwise |, both operands are always evaluated. (I don't think there's any guarantee about which is evaluated first, either; at least, I'm not immediately seeing one in JLS§15.22.2, but perhaps there's a guarantee elsewhere.) With a logical ||, the left-hand operand is evaluated first, and then the right-hand is evaluated only if the left-hand result was false.

This can matter if you're doing something defensive, such as:

boolean flag = obj == null || obj.flag;

That would fail if we used | instead of ||, when obj was null; we'd get a NullPointerException.

Separately, there's the issue that others have to read and work with your code, and using | where || is normally used would be surprising. But that's a matter of style.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875