0

I have created the following example code in Java:

public class SetClassNullExperiment {

    public static void main(String[] args) {
        SetMeNull c1 = new SetMeNull();
        c1.setInputToNull(c1);
        System.out.println("Is c1 equal to null? " + Boolean.toString(c1 == null)); // false
        c1.printHelloWorld();

        SetMeNull c2 = new SetMeNull();
        c2 = null;
        System.out.println("Is c2 equal to null? " + Boolean.toString(c2 == null)); // true
        c2.printHelloWorld(); // Throws a NullPointerException (For obvious reasons...)
    }

}

class SetMeNull {

    /**
     * Set the input class equal to <code>null</code>.
     */
    public void setInputToNull(SetMeNull c) {
        c = null;
    }

    public void printHelloWorld() {
        System.out.println("Hello World!");
    }

}

Why is it possible to call c1.printHelloWorld() after c1.setInputToNull(c1) has been called? I would expect a NullPointerException when calling c1.printHelloWorld(). Why is this not the case? In my opinion, the first four lines (c1) are equal to the last four lines (c2), but only in the last four lines a NullPointerException is thrown.

NicoHahn
  • 23
  • 5

1 Answers1

2

The two examples aren't the same. In the first, you're setting a copy of the reference to null (see, e.g. this). If you were to call the method on c inside setInputToNull, you'd get the NPE there.

ndc85430
  • 1,395
  • 3
  • 11
  • 17