Short-circuit AND Operator

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 evaluates to false

Short-circuit AND Operator

AND Operator &&
true  && true  true
false && true  false true  && false  false false && false false

You may have noticed something in answering the question: you can get the correct answer to the question by evaluating just the first part of the expression:

12 < 6 && 18 > 1
------ 
false

Since false && anything is false, there is no need to continue after the first false has been evaluated. In fact, this is how Java operates:

To evaluate X && Y, first evaluate X. If X is false then stop: the whole expression is false. Otherwise, evaluate Y then AND the two values.

This idea is called short-circuit evaluation. Programmers frequently make use of this feature. For example, say that two methods that return true/false values are combined in a boolean expression:

if ( methodThatTakesHoursToRun() && methodThatWorksInstantly() )
   ....

QUESTION 2:

Suggest a better (but logically identical) way to arrange this boolean expression.