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();

The output of that line was of course:

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.


Skip down to comments...
Hope you found this post useful...

...so please read on! I love writing articles that provide beneficial information, tips and examples to my readers. All information on my blog is provided free of charge and I encourage you to share it as you wish. There is a small favour I ask in return however - engage in comments below, provide feedback, and if you see mistakes let me know.

If you want to show additional support and help me pay for web hosting and domain name registration, donations, no matter how small, are always welcome!

Use of any information contained in this blog post/article is subject to this disclaimer.
comments powered by Disqus
Other posts you may like...