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);
Since your method
sum(final long... values)
uses primitives, you can't simply put Long values inside the method when they arenull
.For valid Long-values this happens:
For non-valid Long-values this happens:
Try something like this instead:
Or, if you still want to sum the values and count
null
as0
, use this:Or, change the parameter-type of the
sum
method toLong
instead oflong
and do one of these two checks inside the method.