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:07

A side note: Java has |= but not an ||=

An example of when you must use || is when the first expression is a test to see if the second expression would blow up. e.g. Using a single | in hte following case could result in an NPE.

public static boolean isNotSet(String text) {
   return text == null || text.length() == 0;
}
查看更多
明月照影归
3楼-- · 2018-12-31 18:10

|| returns a boolean value by OR'ing two values (Thats why its known as a LOGICAL or)

IE:

if (A || B) 

Would return true if either A or B is true, or false if they are both false.

| is an operator that performs a bitwise operation on two values. To better understand bitwise operations, you can read here:

http://en.wikipedia.org/wiki/Bitwise_operation

查看更多
像晚风撩人
4楼-- · 2018-12-31 18:11

Take a look at:

http://java.sun.com/docs/books/tutorial/java/nutsandbolts/operators.html

| is bitwise inclusive OR

|| is logical OR

查看更多
初与友歌
5楼-- · 2018-12-31 18:12

The operators || and && are called conditional operators, while | and & are called bitwise operators. They serve different purposes.

Conditional operators works only with expressions that statically evaluate to boolean on both left- and right-hand sides.

Bitwise operators works with any numeric operands.

If you want to perform a logical comparison, you should use conditional operators, since you will add some kind of type safety to your code.

查看更多
墨雨无痕
6楼-- · 2018-12-31 18:12

The basic difference between them is that | first converts the values to binary then performs the bit wise or operation. Meanwhile, || does not convert the data into binary and just performs the or expression on it's original state.

int two = -2; int four = -4;
result = two | four; // bitwise OR example

System.out.println(Integer.toBinaryString(two));
System.out.println(Integer.toBinaryString(four));
System.out.println(Integer.toBinaryString(result));

Output:
11111111111111111111111111111110
11111111111111111111111111111100
11111111111111111111111111111110

Read more: http://javarevisited.blogspot.com/2015/01/difference-between-bitwsie-and-logical.html#ixzz45PCxdQhk

查看更多
浅入江南
7楼-- · 2018-12-31 18:13

a | b: evaluate b in any case

a || b: evaluate b only if a evaluates to false

查看更多
登录 后发表回答