NoSingleLogicAnd

Misconception:

While && is a logical AND, & is a bitwise AND.

Incorrect

& is only a bitwise AND

Correct

& for boolean operands is a logical AND

Correction
Here 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) {
  //...
}

Symptoms
How 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.

Stay up-to-date

Follow us on  twitter to hear about new misconceptions.