File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes doubt on toString() method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "doubt on toString() method" Watch "doubt on toString() method" New topic
Author

doubt on toString() method

Ashok Pradhan
Ranch Hand

Joined: Dec 17, 2007
Posts: 180

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
Sheriff

Joined: Sep 28, 2004
Posts: 18763
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Ashok Pradhan
Ranch Hand

Joined: Dec 17, 2007
Posts: 180

Thanks Henry,now I got it
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: doubt on toString() method