What is the difference between & and && in Java?

前端 未结 13 2725
感情败类
感情败类 2020-11-22 10:33

I always thought that && operator in Java is used for verifying whether both its boolean operands are true, and the & oper

13条回答
  •  天命终不由人
    2020-11-22 11:11

    Besides && and || being short circuiting, also consider operator precedence when mixing the two forms. I think it will not be immediately apparent to everybody that result1 and result2 contain different values.

    boolean a = true;
    boolean b = false;
    boolean c = false;
    
    boolean result1 = a || b && c; //is true;  evaluated as a || (b && c)
    boolean result2 = a  | b && c; //is false; evaluated as (a | b) && c
    

提交回复
热议问题