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

前端 未结 13 2697
感情败类
感情败类 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:15

    all answers are great, and it seems that no more answer is needed but I just wonted to point out something about && operator called dependent condition

    In expressions using operator &&, a condition—we’ll call this the dependent condition—may require another condition to be true for the evaluation of the dependent condition to be meaningful.

    In this case, the dependent condition should be placed after the && operator to prevent errors.

    Consider the expression (i != 0) && (10 / i == 2). The dependent condition (10 / i == 2) must appear after the && operator to prevent the possibility of division by zero.

    another example (myObject != null) && (myObject.getValue() == somevaluse)

    and another thing: && and || are called short-circuit evaluation because the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression

    References: Java™ How To Program (Early Objects), Tenth Edition

提交回复
热议问题