Explanation and fix for Possible null pointer dereference of

Aravind Yarram picture Aravind Yarram · Jul 27, 2011 · Viewed 29.8k times · Source

Code review tool is complaining Possible null pointer dereference of safeScanWarnings in saveSafeScan(...) At the line if (safeScanWarnings != Null & safeScanWarnings.size() > 0)

I am wondering how is this possible? Is this because we are returning the collection by reference?

protected void saveSafeScan(final Response response, final Dtec dtec) throws dtecException
    {
        Collection<String> safeScanWarnings = dtec.getSafeScanWarnings();
        if (safeScanWarnings!=null && safeScanWarnings.size()>0)
        {
            Iterator<String> iterator = safeScanWarnings.iterator();

            int i = 0;
            while (iterator.hasNext())
            {
                String safeScanCode = iterator.next();
                if (i == 0)
                {
                    response.setSafeScanCode(safeScanCode);
                    response.setSafeScanCodeText(getMessage(String.format("DTECRESPONSE_SAFESCANCODE_%s",
                            StringUtils.trimToEmpty(safeScanCode))));
                }
                SafeScanWarning safeScan = new SafeScanWarning();
                safeScan.setCode(safeScanCode);
                safeScan.setMessage(String.format("DTECRESPONSE_SAFESCANCODE_%s", StringUtils.trimToEmpty(safeScanCode)));
                safeScan.setPriority(i);
                response.getSafeScanWarnings().add(safeScan);
                i++;
            }
        }
    }

Answer

Jon Skeet picture Jon Skeet · Jul 27, 2011

If it's really pointing to that line, it looks like a bug in the code review tool to me.

As it's a local variable, there's no chance that it'll be changed by anything else between the nullity check and the size() call - so there's no way it'll throw a NullPointerException.