aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Why do I not get a NullPointerException when I try to print a null String? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Why do I not get a NullPointerException when I try to print a null String?" Watch "Why do I not get a NullPointerException when I try to print a null String?" New topic
Author

Why do I not get a NullPointerException when I try to print a null String?

Joe Lemmer
Ranch Hand

Joined: Oct 24, 2008
Posts: 171
Hi there,

I was just wondering why I don't get a null pointer exception when I try to print a null String object like so:



I thought that println() used an object's toString() method, but if there is no String object as in the above example then you can't call it's toString() method. So I thought that in this case I would get a NullPointerException thrown as happens in other circumstances when trying to access an object that doesn't exist.

Any thoughts?

Many thanks

Joe


OCPJP 85%
Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

Go through the println() method's API.


|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
lakmal padmakumara
Ranch Hand

Joined: Aug 08, 2009
Posts: 47
Change to


Do you get idea now ?


[Bsc in Computer Science and Engineering] [SCJP 80%][BCS certificate level]
Joe Lemmer
Ranch Hand

Joined: Oct 24, 2008
Posts: 171
Thanks for your replies guys.

According to the API:

Prints a string. If the argument is null then the string "null" is printed.


So, as I understand it, the reason we don't get a NullPointerException thrown is because the println() method specifically handles the null case, whereas this is not the case in many other methods.
Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

So you got it!
Joe Lemmer
Ranch Hand

Joined: Oct 24, 2008
Posts: 171
Thanks Abimaran
Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

Joe Lemmer wrote:Thanks Abimaran


You are WelCome
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why do I not get a NullPointerException when I try to print a null String?