NoShortCircuit
&&
is a logical AND and ||
is a logical OR,
and both always evaluate both of their operands.
&& and || always evaluate both operands
&& and || evaluate their right operand only if absolutely necessary
CorrectionHere is what's right.
Those two operators are short-circuit operators, which means they first evaluate the left operand and then only evaluate the right operand if that’s really necessary.
SymptomsHow do you know your students might have this misconception?
This misconception can be observed in cases where the operands cause side effects:
boolean tru() {
print("T");
return true;
}
boolean fls() {
print("F");
return false;
}
tru() || fls() // "T" -- students claim "TF"
tru() | fls() // "TF"
fls() && tru() // "F" -- students claim "FT"
fls() & tru() // "FT"
ValueHow can you build on this misconception?
Use in a common idiom
This misconception provides an opportunity to discuss the following idiom,
which would cause a NullPointerException
if &&
always evaluated its right-hand operand:
if (o!=null && o.isGood()) ...
Evaluation strategies
This misconception can also be a great segway into a discussion of the idea of evaluation strategies (a central concept in programming languages). In Java, most operators are evaluated in a strict way: they always evaluate all their operands.
// most operators:
o1 OPERATOR o2 // eval o1, eval o2
o1 & o2 // eval o1, eval o2
o1 | o2 // eval o1, eval o2
// special operators:
o1 && o2 // eval o1, maybe eval o2
o1 || o2 // eval o1, maybe eval o2
o1 ? o2 : o3 // eval o1, either eval o2 or eval o3
The two short-circuit operators, and the ternary conditional operator ?:
,
are evaluated in a more lazy way:
while they do first evaluate their left operand (o1
above),
&&
and ||
only evaluate their right operand (o2
) if needed,
and ?:
only evaluates either o2
or o3
, based on the value of o1
.
Language
Concepts
Expressible In
Related Misconceptions
Other Languages
Literature References
Repository mining study (BlueJ Blackbox)
250000+ students across the world
Qualitative (survey of instructors and students)
Unknown number of undergraduate students, professors, SIGCSE members