I want to understand why the following code throws Null pointer exception.
import java.util.List;
public class Test {
public static void main(String[] args) {
List<String> names = null;
System.out.println("Result is: " + names == null ? null : names.size());
}
}
When there is more than one arithmetic operator in an expression; multiplication, division, and modulo are calculated first, followed by subtraction and addition. If all arithmetic operators in an expression have the same level of precedence, the order of execution is left to right.
For example, in mathematics and most computer languages, multiplication is granted a higher precedence than addition, and it has been this way since the introduction of modern algebraic notation.
The issue is that your print statement is evaluated as:
System.out.println(("Result is: " + names) == null ? null : names.size());
This is due to the fact that +
has more precedence than ?:
operator So, as the string - "Result is null" is not equal to null
, evaluating names.size()
throws NPE.
Note that, when null
is used in string concatenation, it is automatically converted to "null"
. So, "Result is: " + null
will not throw NPE
. This is as per JLS - String Conversion:
If the reference is
null
, it is converted to the string"null"
(four ASCII characters n, u, l, l).
To fix the issue, you should add parenthesis around your conditional expression to enforce greater precendence to it:
System.out.println("Result is: " + (names == null ? null : names.size()));
Correcting Jigar's answer, this actually works:
someString + null
To fix OP's code, just add parenthesis - in this way the operations will be performed in the correct order and the result will be as expected:
System.out.println("Result is: " + (names == null ? null : names.size()));
you are writing "Result is: " + names which is not equivalent to null so its trying to print names.size()
. But when names.size()
is called it throw null pointer exception as names is still null.
Modify
System.out.println("Result is: " + names == null ? null : names.size());
to
System.out.print("Result is: ");
System.out.println( names == null ? null : names.size());
then you will get null as output.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With