Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Joe Lemmer
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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

 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Go through the println() method's API.
 
lakmal padmakumara
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Change to


Do you get idea now ?
 
Joe Lemmer
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So you got it!
 
Joe Lemmer
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Abimaran
 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Joe Lemmer wrote:Thanks Abimaran


You are WelCome
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic