NoSingleLogicAnd
& is only a bitwise AND
& for boolean operands is a logical AND
CorrectionHere is what's right.
While &
can be a bitwise AND (e.g., 1&3 == 1
),
&
is also a logical AND (e.g., true&false == false
).
boolean a = false;
boolean b = true;
boolean c = a & b; // logical and - perfectly legal in Java
boolean a = false;
boolean b = true;
boolean c = a && b; // logical and (short-circuit) - perfectly legal in Java
int a = 1;
int b = 3;
int c = a & b; // bitwise and - perfectly legal in Java
&&
is a short-circuit logical AND,
and &
is an eager logical AND.
Eager means that &
always evaluates both its operands before it produces a value.
The lazy short-circuit &&
first evaluates its left operand,
and if that is false
,
then it does not evaluate its right operand and simply produces false
.
It only evaluates its right operand
if the first operand evaluates to true
.
This is very useful,
e.g., for conditions like the following,
because it prevents the NullPointerException
that would be thrown if o.get()
had to be evaluated:
if (o != null && o.get() > 0) {
//...
}
SymptomsHow do you know your students might have this misconception?
If students claim that &
is “bitwise and” (for int
)
and &&
is “logical and” (for boolean
),
then they probably also believe that &
cannot work with boolean
operands.
Language
Concepts
Expressible In
Related Misconceptions
Literature References
The following papers directly or indirectly provide qualitative or quantitative evidence related to this misconception.
Repository mining study (BlueJ Blackbox)
250000+ students across the world
Mistakes studied:
Qualitative (survey of instructors and students)
Unknown number of undergraduate students, professors, SIGCSE members
Errors studied: