29 January 2013

Once in a while I come across Java code bases where the a reference to a just created object is checked against null.
Often this occurs in unit tests like the following:

Foo foo = new Foo();

This is nonsense. An object creation never returns null. If something fails when instanciating the object, an exception is thrown.
Even if not enough memory is available to create the object an OutOfMemoryError is thrown instead.

BTW, this is different in languages like Objective-C and Smalltalk where the class instantiating methods (init, new) are ordinary class level methods which can of course return nil.

I recommend reading Object Initialization in Java by Bill Venners to get a deep understanding of this stuff.