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 :)
}
}