Short-circuit OR

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   hear noise   go to next page

Answer:

12 > 6 || 18 > 1
------ 
true

Short-circuit OR

ExpressionResultEvaluation Order
true || true true only first operand evaluated
false || true true both operands evaluated
true || false true only first operand evaluated
false || false false both operands evaluated
true | true true both operands evaluated
false | true true both operands evaluated
true | false true both operands evaluated
false | false false both operands evaluated

Perhaps you noticed that to answer the question you only needed to evaluate the first subexpression:

12 > 6 || 18 > 1
------ 
true

Once you know that this subexpression is true there is no need to go further. true OR anything is true.

The || OR operator is also a short-circuit operator. Since OR evaluates to true when one or both of its operands are true, short-circuit evaluation stops with the first true.

The OR operator comes in a non-short-circuit version as well: | (this is a single vertical bar.) When this operator is used, both operands are evaluated no matter what the outcome of the first operand. The short-circuit OR works like this:

To evaluate X||Y, first evaluate X. If X is true then stop: the whole expression is true. Otherwise evaluate Y and OR the two values.

As with the short-circuit AND, be careful when using methods that have side effects. If you are depending on a method's side effect, be sure that the method executes.


QUESTION 8:

What is the value of:

(4 < 8 ) && (12 <= 40 ) && (50 > 1)