DRAFT
NoLocalVariables
Misconception:
It is not possible to declare variables inside methods. If one needs a variable, one can declare one as an instance variable.
Incorrect
There are no local variables
Correct
CorrectionHere is what's right.
Here is what's right.
One can declare local variables inside a method body.
Examples
Here a student used the tail reference in a linked list node as a temporary to iterate over all nodes of the list (thereby mutating the head of the list):
while (this.tail!=null) {
//…
this.tail = this.tail.tail;
}
In the following examples it is not clear whether the students had this misconception, or whether they declared variables (sum
and k
) as a fields because they wanted to accumulate a result across recursive calls:
class IntList {
private int sum;
//...
public int sum() {
while (next != null) {
sum = sum + value;
}
if (next==null) {
sum = sum + value
}
return sum;
}
}
class IntList {
int k = 0 // variable declared as instance variable
//...
public int length() {
if (list==null) {
return k;
} else {
k++
list.child.length()
}
}
}
Language
Java