Can Constructor Return a Null Object?

While looking through some old code I came across this gem:

MyObject o = new MyObject("parameter");
if (o == null) o = new MyObject("fallback parameter");

The second line is marked in Eclipse as dead code, and I understand why. No exception seems to be explicitly thrown, and it isn't possible for the MyObject constructor to throw any kind of exception (such as NullPointerExceptions).

My question is why there is a null check? Was it previously possible in an old version of Java for a constructor to return null? Or is this simply useless and dead code?

4

11 Answers

The code is dead in any version of Java. It's not possible for a constructor to return null, and even if an exception would be thrown from the constructor, the next line won't be called.

No, it has never been possible. Maybe a previous version of the code used some factory method which could return null:

MyObject o = createMyObject("parameter");
if (o == null) o = createMyObject("fallback parameter");

From section 15.9.4 of the JLS:

The value of a class instance creation expression is a reference to the newly created object of the specified class. Every time the expression is evaluated, a fresh object is created.

So no, it can never return null.

4

My guess is that it was written by a C programmer who is used to testing the return value of malloc() for NULL, malloc() can return NULL if your system runs out of memory.

The code doesn't make sense in Java since Java will throw an OutOfMemoryError` if it runs out of memory.

3

The answer is simple: person who wrote the code was a paranoid c++ programmer. In C++ you may overload operator new and use it as a simple memory allocator (aka malloc).

As I discovered today, despite what's said in all the other answers, Foo x = new Foo(...) can indeed return null, if said code is running inside a test that uses PowerMock (or some other mocking framework with similar effects):

PowerMockito.whenNew(Foo.class).withAnyArguments().thenReturn(mockFoo);

In this case, the code in the constructor(s) of Foo is bypassed altogether for new Foo(...). But if you write a test where you fail to specify the mock in the manner above, you may end up with null instead.

But even if you are using such a framework, you don't want extra code in your classes, just to gracefully handle the case that you forgot to properly mock the objects in a test! It is not a real-world scenario where your code is intended to run. Code that is only ever active when testing should be eliminated anyway, and in this case it would only ever be active for a broken test.

So even if you're using PowerMock, that second line should rightly be considered "dead code" and removed.

This was simply usesless dead code. Once CTOR has executed successfully, you have reference to the object.

When you create a new Object(), you create an address in memory, and this address is not 'null', but your Object may be empty.

You have to test 'null' for Object transmitted by parameters.

It's simply dead code.

new MyObject("parameter") will not return null in any version of java.

The question is absolutely legitimate. You can add a static method in MyObject like so:

static MyObject create(String parameter)) {
       if (parameter.satisfySomething())
          return new MyObject(parameter);
       else
          return null;
}

All the answers are based on theoretical and editor's warnings.

Indeed most editors will report a dead code when testing the results of a new object() against null.

However, at least on Android, I have many crash reports of a new xxx() returning null, and I assume because of lack of memory in most cases.

A simple example is like so:

object_class obj = new object_class(context);
obj.getCount();

And I get such report on the getCount() line:

java.lang.NullPointerException: Attempt to invoke virtual method 'int object_class.getCount()' on a null object reference

So it's possible, but most editors/compilers won't let you check for such condition.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.

Share this article
Twitter Facebook Pinterest