0

Some explaination about the following snippets:
I'm messing with some Bluetooth discovery calls. For that I'm using a callback, which will be invoked if a BluetoothDevice is found or not. If no device was found the parameter is null:

@Override
public void provideDevice(BluetoothDevice device) {
    super.provideDevice(device);
    Log.v("MainActivity","device name = " +device.getName());
    if(device != null) {

        mBinder.start(device);

    } else { 

        Toast.makeText(this, "No Device found", Toast.LENGTH_SHORT).show();

    }
}

Eclipse is telling me that the else block is dead code.

If I move the Log call in the if-block the warning is gone:

@Override
public void provideDevice(BluetoothDevice device) {
    super.provideDevice(device);

    if(device != null) {

        Log.v("MainActivity","device name = " +device.getName());
        mBinder.start(bc);

    } else { 

        Toast.makeText(this, "No Device found", Toast.LENGTH_SHORT).show();

    }
}

I know that the first snippet will throw a NPE if the parameter is null. That's not the problem in this example.

I would like to know why the dead code warning appears.

I can provide the full code, if this isn't enough to tell me what's going on.

Steve Benett
  • 12,843
  • 7
  • 59
  • 79

2 Answers2

5

You dereference device in the log statement.

If you get past that line of code, device cannot be null, because you'd get an NPE if it was.

This means the else statement is redundant, because if the code gets that far, it can't be null.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • From where should the compiler know that the parameter is null and I made a mistake in my code by risking a NPE? Is the compiler really thinking "The programer knows what he is doing"? – Steve Benett Nov 09 '13 at 15:28
  • @SteveBenett The compiler is saying "it's been dereferenced; it can no longer be null in this code path"--because the only way to get that far is to *not* have an NPE. It's not so much that it's assuming we know what we're doing, rather that it will only make assumptions it *knows* it can make (and it won't make *all* assumptions it *could* make, either). – Dave Newton Nov 09 '13 at 15:37
1

Your problem is that, in the first example, Java knows that it is impossible for device != null to be false, since if it were null, you would have gotten an NPE from the log statement, and would not reach that code.

mattdee123
  • 213
  • 1
  • 5
  • 11