Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.

NOTE: This article is 3 years or older so its information may no longer be relevant. Read on at your own discretion! Comments for this article have automatically been locked, refer to the FAQ for more details.
I was looking at some Java code recently that got me stuck for quite some time. It seemed to be doing the impossible, getting a null reference when creating a new object. I was starting to think that maybe there is something wrong with the JDK, then I've created a new object of a similar type that worked ok, but the original object was still being created as a null reference. This was very confusing, but the answer to why this was happening was a very simple mistake in the code.

The code similar to below was being used to show the object creation:
ObjectNull obj = new ObjectNull();
System.out.println(obj);


The output of that line was of course:
null


What was going on, this is seemingly impossible!

Digging further into the code, the offending line was in the toString() method!
...
public String toString() {
return null;
}
...


Now it all made sense! The object was being created properly, it was simply because the toString() method was implemented that the output of null was being displayed.

So the answer is you can't get a null from a Java constructor and if that is what you are seeing, check what the toString() is doing.



-i

Skip down to comments...
A quick disclaimer...

Although I put in a great effort into researching all the topics I cover, mistakes can happen. If you spot something out of place, please do let me know.

All content and opinions expressed on this Blog are my own and do not represent the opinions of my employer (Oracle). Use of any information contained in this blog post/article is subject to this disclaimer.
 
comments powered by Disqus
Other posts you may like...