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

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

A quick disclaimer...

Although I put in a great effort into researching all the topics I cover, mistakes can happen. Use of any information from my blog posts should be at own risk and I do not hold any liability towards any information misuse or damages caused by following any of my posts.

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.
Hi! You can search my blog here ⤵
NOTE: (2022) This Blog is no longer maintained and I will not be answering any emails or comments.

I am now focusing on Atari Gamer.