What are the cases in which it is better to use unconditional AND (& instead of &&)

后端 未结 11 697
没有蜡笔的小新
没有蜡笔的小新 2020-11-28 10:33

I\'d like to know some cases in Java (or more generally: in programming) when it is preferred in boolean expressions to use the unconditional AND (&

11条回答
  •  生来不讨喜
    2020-11-28 11:00

    The && allows the jvm to do short circuit evaluation. That is, if the first argument is false, then it doesn't need to bother checking the second argument.

    A single & will run both sides regardless.

    So, as a contrived example, you might have:

    if (account.isAllowed() & logAccountAndCheckFlag(account))
        // Do something
    

    In that example, you might always want to log the fact that the owner of the account attempted to do something.

    I don't think I have ever used a single & in commercial programming though.

提交回复
热议问题