Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java OR operator precedence

How to chain conditional statements in Java in a way that if b is false, than do not check c?

If a and c are false, and b is true, does c will be checked?

if (a || b || c)

I am looking for similar feature that PHP holds with difference between OR and ||

like image 548
Szymon Toda Avatar asked Jan 18 '14 09:01

Szymon Toda


People also ask

Which has higher precedence in Java?

In Java, parentheses() and Array subscript[] have the highest precedence in Java. For example, Addition and Subtraction have higher precedence than the Left shift and Right shift operators.

Which has the highest precedence () or?

The logical-AND operator ( && ) has higher precedence than the logical-OR operator ( || ), so q && r is grouped as an operand.

What is meant by operator precedence?

Operator Precedence ¶ The precedence of an operator specifies how "tightly" it binds two expressions together. For example, in the expression 1 + 5 * 3 , the answer is 16 and not 18 because the multiplication ("*") operator has a higher precedence than the addition ("+") operator.


2 Answers

The Java || operator (logical or operator) does not evaluate additional arguments if the left operand is true. If you wanted to do that, you can use | (bitwise or operator), although, according to the name, this is a little of a hack.

http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.23

Thus, && computes the same result as & on boolean operands. It differs only in that the right-hand operand expression is evaluated conditionally rather than always.

http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.24

Thus, || computes the same result as | on boolean or Boolean operands. It differs only in that the right-hand operand expression is evaluated conditionally rather than always.

Extra: it is considered bad programming style to depend on these semantics to conditionally call code with side effects.

like image 65
Silly Freak Avatar answered Oct 06 '22 17:10

Silly Freak


if (a || b || c)

for you case,

a is true then b and c not checked.

a is false and b is true then c not checked.

a and b are false then c is checked.

the left side of the operator is evaluated first

like image 27
Rakesh Chaudhari Avatar answered Oct 06 '22 18:10

Rakesh Chaudhari