Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

doubt on toString() method

 
Ashok Pradhan
Ranch Hand
Posts: 180
Eclipse IDE Firefox Browser Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Object o=null;
System.out.println(o); //prints null

My doubt is when we want to print an object then the toString() method of the object is called on that object.but here reference variable o is null,so when the toString() method is called on System.out.println(o.toString()); then it should throw NPE.

clarify my doubt why it prints null instead of NPE.
 
Henry Wong
author
Marshal
Pie
Posts: 20905
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ashok Pradhan:
Object o=null;
System.out.println(o); //prints null

My doubt is when we want to print an object then the toString() method of the object is called on that object.but here reference variable o is null,so when the toString() method is called on System.out.println(o.toString()); then it should throw NPE.

clarify my doubt why it prints null instead of NPE.


It's quite simple, the println() method checks for null, before calling the toString() method. If it is null, then it uses "null" as the string to print.

When you call toString() directly, you didn't check for null, hence, it threw an NPE.

Henry
 
Ashok Pradhan
Ranch Hand
Posts: 180
Eclipse IDE Firefox Browser Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Henry,now I got it
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic