IfRequiresElse
DRAFT
Observed

IfRequiresElse
Incorrect

Every if statement requires an else

Correct

If statements do not necessarily require an else

Correction
Here is what's right.

In Java it is perfectly legal to have if statements without else.

However, the conditional operator (c ? et : ef) does require expressions for both cases (et and ef). This is because the conditional operator is an expression, and thus it must produce a value no matter whether the condition is true. An if statement does not have that requirement, because it is a statement, and thus it does not produce any value.

Example

Here we see an occurrence where the student added an else containing an assignment that changes nothing:

int count(int[] values, int value) {
  for (int v : values) {
    if (v==value) {
      count = count + 1;
    } else { // else branch is not necessary
      count = count;
    }
  }
}

This probably comes from learning to program in a pure functional language, where everything is an expression.