Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between OR operator || and | in Java? [duplicate]

Tags:

java

Can any one explain the difference between and usage of OR operator ( || and | ) in java. thanks

e.g:

if(a || b) {
// Do something.
}

and

if(a | b) {
// Do something.
}
like image 543
AKZap Avatar asked May 31 '26 11:05

AKZap


2 Answers

This is simple. http://www.roseindia.net/help/java/o/java-operator.shtml says:

OR operator is a kind of a conditional operators, which is represented by | symbol. It returns either true or false value based on the state of the variables i.e. the operations using conditional operators are performed between the two boolean expressions.

The OR operator (|) is similar to the Conditional-OR operator (||) and returns true, if one or another of its operand is true.

Note: In || operator if have more than one condition and if first condition return true then other conditions ignored but in | operator all condition examin.

There are more information on http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

like image 125
Sam Avatar answered Jun 02 '26 01:06

Sam


The first one is a logical or. Both sides of the operator are handled as boolean values and it results in a boolean. In case the variables in question are not boolean themselves they become false if they are 0 or null.

The second one is a bit-wise or operator. This one usually only works with integer numbers. I compares the two values bit by bit and gives the resulting number. For example:

5   | 6   = 7    (decimal)
101 | 110 = 111  (binary)

For further details have a look at Wikipedia: Logical disjunction

like image 20
Nitram Avatar answered Jun 01 '26 23:06

Nitram



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!