3

I'm using Java 1.7.0_79

The code in questions is this and I am instantiating a new object, and I want to check if the object has a valid reference after the constructor returns, I check to see if it is null:

 mClientConnection = null;
 mClientConnection = new XMPPTCPConnection(configBuilder.build());
 if(mClientConnection == null) {
    return false;
 }

The constructor implementation contains this:

public XMPPTCPConnection(XMPPTCPConnectionConfiguration config) {
    super(config);
    this.config = config;
}

I am wondering how can I check that the mClientConnection contains a valid reference?

I am using findbugs and I get this reported error:

This method contains a redundant check of a known non-null value against the constant null

Mat
  • 202,337
  • 40
  • 393
  • 406
ant2009
  • 27,094
  • 154
  • 411
  • 609
  • http://stackoverflow.com/questions/11103444/java-can-creating-an-object-return-a-null-reference - you're trying to test for something that can't happen. – Mat May 03 '15 at 06:34

3 Answers3

3

The findbugs warning is correct, because the constructor can never return null. At the worst case it might throw an exception, but then it won't get to that last line where you check for null.

Pelit Mamani
  • 2,321
  • 2
  • 13
  • 11
3

If you want to test for validity you need to add a method which does this.

mClientConnection = new XMPPTCPConnection(configBuilder.build());
if (!mClientConnection.isValid())
    return false;

What makes a component valid depends on what it is and does and you can write that in a method.

Once you set the value of a variable from a new object you can assume it is not null (unless you are setting it to null in another thread)

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
3

It's not the constructor that returns the newly created object. A constructor does not return anything - it has no return type and no return statement.

When you create a new object with the new operator, then the Java runtime environment will allocate memory for the object and initialize it by calling the appropriate constructor. The new operator then returns a reference to the object - not the constructor.

The new operator never returns null, so it is never necessary to check if the reference is null right after using new.

Jesper
  • 202,709
  • 46
  • 318
  • 350