-3

This might sound funny or baseless to some . Forgive me for that :)

I have overridden a toString() method in java to see contents of the object created and it works fine with valid objects created . My doubt is shouldn't it throw a NullPointerException when I call the toString() method with a null reference .

Below is my code snippet

public class Test {

    String name;
    public Test(String naam) {
        name = naam;
    }

    @Override
    public String toString() {
        return name;
    }

    void Display() {
        System.out.println("Display "+ name);
    }

    public static void main(String[] args) {

        Test validName = new Test("som");
        System.out.println("toString "+validName);
        validName.Display();

        validName = null;
        System.out.println(validName); // Prints "null" . Why doesnt it throw a NPE ?
        validName.Display(); // throws NPE for obvious reasons :) 
    }

}
Vivek Singh
  • 2,047
  • 11
  • 24
darkHorse
  • 13
  • 8

1 Answers1

1

println specially handles nulls. System.out is just a static reference of type PrintStream, and the docs for PrintStream::println(Object) state:

This method calls at first String.valueOf(x) to get the printed object's string value ...

Tracing it down, String::valueOf(Object)'s javadoc state:

Returns: if the argument is null, then a string equal to "null" ...

yshavit
  • 42,327
  • 7
  • 87
  • 124