Help with S2259 NullPointerException

Which versions are you using

SonarQube: 7.9.4

What are you trying to achieve

Resolve violation of rule S2259: A “NullPointerException” could be thrown; “bar” is nullable here.

What have you tried so far to achieve this

Code is as follows (this is the exact method, I have changed only the symbol names and comparison string value in .contains()).

public boolean isFoo(String bar) {
        if (bar != null || bar.isEmpty()) {
            return bar.contains("foobar") ;
        return false;

Line #2 triggers the following major bug for both conditions in the if statement: A “NullPointerException” could be thrown; “bar” is nullable here.

Yes of course the String is nullable, that is exactly what is being checked for!
Obviously I am not understanding what SQ expects to see here, could someone please enlighten?

Thank you

Pretend you’re a JVM, executing this code line by line. Assume for this test case that bar is null. Walk through each line and condition. If bar is null, then “bar != null” will be false. If that’s the case, then it will attempt to evaluate the next condition, being “bar.isEmpty()”, which will then throw a NullPointerException.

The line likely should have been:

if (bar != null && bar.isNotEmpty()) {

If you have the commons-lang library in scope, then this might be even better:

if (StringUtils.isNotBlank(bar)) {
1 Like

I thought JVM would shortcut on AND conditions?
i.e. if the first one is false because bar is indeed null, then it automatically “knows” that it does not need to bother evaluating the second condition?

You’re dead on with the missing Not though !

Sure, the JVM will do “short-circuiting” for logical operations. It will do that for ANDs and ORs, but you don’t have an AND, you have an OR. The algorithm is different for ANDs and ORs.

1 Like

Thanks David - A case of not seeing the wood for the trees!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.