multiple null arguments to a method taking varargs causes null pointer exception

345 views Asked by At

I run into a null pointer exception when i run this:

public class test {
    public static void main(String[] args) {
        Long a = getValue();
        Long b = getValue();
        Long c = sum(a, b);
    }

    private static Long getValue() {
        return null;
    }

    private static long sum(final long... values) {
        long sum = 0L;
        for(final long value: values) {
            sum += value;
        }
        return sum;
    }
}

The stack trace: Exception in thread "main" java.lang.NullPointerException at com.mypackage.test.main(test.java:10)

Why is the null pointer being thrown at this line: Long c = sum(a, b);

1

There are 1 answers

4
Kevin Cruijssen On BEST ANSWER

Since your method sum(final long... values) uses primitives, you can't simply put Long values inside the method when they are null.

For valid Long-values this happens:

Long value1 = 1L;
Long value2 = 2.0L;
sum(value1, value2);    // value1 and value2 will be unboxed from Long to long, 
                        // and then used in the method

For non-valid Long-values this happens:

Long value1 = null;
Long value2 = null;
sum(value1, value2);     // value1 and value2 will be unboxed from Long to long,
                             // giving an error because they are null, which is not a valid primitive value

Try something like this instead:

Long value1 = null;
Long value2 = null;
if(value1 == null || value2 == null) return; // or something else like continue, logging, etc.
sum(value1, value2);

Or, if you still want to sum the values and count null as 0, use this:

Long value1 = null;
Long value2 = null;
value1 = value1 != null ? value1 : 0L;
value2 = value2 != null ? value2 : 0L;
sum(value1, value2);

Or, change the parameter-type of the sum method to Long instead of long and do one of these two checks inside the method.