• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

doubt on toString() method

 
Ranch Hand
Posts: 180
Netbeans IDE Eclipse IDE Firefox Browser
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
Netbeans IDE Eclipse IDE Firefox Browser
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Henry,now I got it
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic