Can constructor return a null object?

JavaConstructorNull

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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

Solution 3 - Java

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.

Solution 4 - Java

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.

Solution 5 - Java

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).

Solution 6 - Java

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.

Solution 7 - Java

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

Solution 8 - Java

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.

Solution 9 - Java

It's simply dead code.

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

Solution 10 - 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;
}

Solution 11 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJonathan PitreView Question on Stackoverflow
Solution 1 - JavatibtofView Answer on Stackoverflow
Solution 2 - JavaJB NizetView Answer on Stackoverflow
Solution 3 - JavaJon SkeetView Answer on Stackoverflow
Solution 4 - JavaJack EdmondsView Answer on Stackoverflow
Solution 5 - JavakofemannView Answer on Stackoverflow
Solution 6 - JavaZac ThompsonView Answer on Stackoverflow
Solution 7 - JavaYair ZaslavskyView Answer on Stackoverflow
Solution 8 - Javacl-rView Answer on Stackoverflow
Solution 9 - JavaAlex LockwoodView Answer on Stackoverflow
Solution 10 - JavaPhantom LordView Answer on Stackoverflow
Solution 11 - Java3c71View Answer on Stackoverflow