S1066 - with outer null check

For Java code:

if (var != null) {
  if (var.equals(var2)) {
    // action

SonarLint triggers S1066 ‘Collapsible “if” statements should be merged’.

Personally I prefer to keep the null check separate. It may be that the compiler would never throw a NullPointerException for

if ((var != null) && var.equals(var2)) {
 // action

but that seems like a detail of how the compiler works.

If I’m in the minority in this, please feel free to close the bug, but I thought I would report as I’m not sure if it’s intended behaviour or not.

Version used: IDEA plugin

Hi Olivier,

I don’t understand why a null check should be different from other kind of conditions.
And in my option, in your example, it’s the opposite, it makes even more sense to group the two conditions because there are closely linked. Then, it could be even more readable to hide technical details in an utility method like Objects.equals(Object a, Object b) (but returning false if a and b are null).

Purely because a NullPointerException could be thrown if the second test (the equals call) is evaluated before the first.

Or will conditions separated by && always be evaluated left to right by the compiler/JVM?

If so I will switch to writing the conditions that way. As you say, a utility method may be even better.

To answer my own question, it looks like that is the case:

I guess this can be closed!