Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean expression order of evaluation in Java?

Suppose I have the following expression

String myString = getStringFromSomeExternalSource(); if (myString != null && myString.trim().length() != 0) { ... } 

Eclipse warns me that myString might be null in the second phrase of the boolean expression. However, I know some that some compilers will exit the boolean expression entirely if the first condition fails. Is this true with Java? Or is the order of evaluation not guaranteed?

like image 779
daveslab Avatar asked Jan 08 '10 15:01

daveslab


People also ask

What is the order of Boolean expression of evaluation?

The order of operations for Boolean algebra, from highest to lowest priority is NOT, then AND, then OR. Expressions inside brackets are always evaluated first.

What is the order of the evaluation of the logical operators Java?

In Java, the operands of an operator are always evaluated left-to-right.

Does && or || come first in Java?

The logical-AND operator ( && ) has higher precedence than the logical-OR operator ( || ), so q && r is grouped as an operand. Since the logical operators guarantee evaluation of operands from left to right, q && r is evaluated before s-- .

Does Java evaluate and or or first?

With three exceptions ( && , || , and ?: ), Java evaluates every operand of an operator before the operation is performed. For the logical AND ( && ) and logical OR ( || ) operators, Java evaluate the second operand only if it is necessary to resolve the result. This is known as short-circuit evaluation.


1 Answers

However, I know some that some compilers will exit the boolean expression entirely if the first condition fails. Is this true with Java?

Yes, that is known as Short-Circuit evaluation.Operators like && and || are operators that perform such operations.

Or is the order of evaluation not guaranteed?

No,the order of evaluation is guaranteed(from left to right)

like image 147
Prasoon Saurav Avatar answered Oct 07 '22 16:10

Prasoon Saurav