Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why can I set the class to null and still call methods from it afterwards?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading