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

| Views: 3602
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.


Have comments or feedback on what I wrote? Please share them below! Found this useful? Consider sending me a small tip.
comments powered by Disqus
Other posts you may like...