can you have two conditions in an if statement

后端 未结 6 1525
鱼传尺愫
鱼传尺愫 2020-12-22 13:48

I\'m a beginner in coding. I was recently working with to create a chatting programme where a user will chat with my computer. Here is a part of the code:

Sy         


        
6条回答
  •  悲哀的现实
    2020-12-22 14:04

    You can use logical operators to combine your boolean expressions.

    • && is a logical and (both conditions need to be true)
    • || is a logical or (at least one condition needs to be true)
    • ^ is a xor (exactly one condition needs to be true)
    • (== compares objects by identity)

    For example:

    if (firstCondition && (secondCondition || thirdCondition)) {
        ...
    }
    

    There are also bitwise operators:

    • & is a bitwise and
    • | is a bitwise or
    • ^ is a xor

    They are mainly used when operating with bits and bytes. However there is another difference, let's take again a look at this expression:

    firstCondition && (secondCondition || thirdCondition)
    

    If you use the logical operators and firstCondition evaluates to false then Java will not compute the second or third condition as the result of the whole logical expression is already known to be false. However if you use the bitwise operators then Java will not stop and continue computing everything:

    firstCondition & (secondCondition | thirdCondition)
    

提交回复
热议问题