Java - What is the output: this = null;

Question

What is the output of the following code?


class Student {
  void m1() {
    
    // Invoke the m2() method
    this.m2(); // same as "m2();"
  }

  void m2() {
    this = null;
    System.out.println(this);
    
  }

}

public class Main {
  public static void main(String[] args) {
    Student s = new Student();

    s.m1();
  }
}


Click to view the answer

this = null;// An error. Cannot assign a value to this because it is a constant.

Note

The keyword this is a final reference to the current instance of the class.

Because it is final, you cannot change its value.

Related Quiz