Why do we usually use `||` not `|`, what is the di

2018-12-31 17:30发布

I'm just wondering why we usually use logical OR || between two booleans not bitwise OR |, though they are both working well.

I mean, look at the following:

if(true  | true)  // pass
if(true  | false) // pass
if(false | true)  // pass
if(false | false) // no pass
if(true  || true)  // pass
if(true  || false) // pass
if(false || true)  // pass
if(false || false) // no pass

Can we use | instead of ||? Same thing with & and &&.

27条回答
大哥的爱人
2楼-- · 2018-12-31 18:14

1).(expression1 | expression2), | operator will evaluate expression2 irrespective of whether the result of expression1 is true or false.

Example:

class Or 
{
    public static void main(String[] args) 
    {
        boolean b=true;

        if (b | test());
    }

    static boolean test()
    {
        System.out.println("No short circuit!");
        return false;
    }
}

2).(expression1 || expression2), || operator will not evaluate expression2 if expression1 is true.

Example:

class Or 
{
    public static void main(String[] args) 
    {
        boolean b=true;

        if (b || test())
        {
            System.out.println("short circuit!");
        }
    }

    static boolean test()
    {
        System.out.println("No short circuit!");
        return false;
    }
}
查看更多
临风纵饮
3楼-- · 2018-12-31 18:14

| = bitwise or, || = logic or

查看更多
皆成旧梦
4楼-- · 2018-12-31 18:16

Logical || and && check the right hand side only if necessary. The | and & check both all the time.

For example:

int i = 12;
if (i == 10 & i < 9) // It will check if i == 10 and if i < 9
...

Rewrite it:

int i = 12;
if (i == 10 && i < 9) // It will check if i == 10 and stop checking afterward because i doesn't = 10
...

Another example:

int i = 12;
if (i == 12 | i > 10) // It will check if i == 12 and it will check if i > 10
...

Rewrite it:

int i = 12;
if (i == 12 || i > 10) // It will check if i == 12, it does, so it stops checking and executes what is in the if statement
...
查看更多
登录 后发表回答