ThisCanBeNull
DRAFT

Misconception:

The special variable this can have the value null.

Incorrect

this can be null

Correct

this is never null

Correction
Here is what's right.

The this variable (a special local variable) never is null. The variable exists during activations of instance methods, and it always points to the instance on which the method operates. That instance always exists, thus the this variable never is null.

Example

The following code was produced by a student as part of a linked list implementation (after seeing a different implementation using a sentinel/null object, and having to produce an implementation that does not use a null object to terminate the list):

public class IntList {

  private int value;
  private IntList tail;

  public int length() {
    if (this==null) {
      return 0;
    } else if (this.tail == null) {
      return 1;
    } else {
      this.tail.length();
    }
  }
}

Stay up-to-date

Follow us on  twitter to hear about new misconceptions.