5

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()); } } 
1
  • Maybe you want names == null ? 0 : names.size() Commented Sep 5, 2013 at 5:16

3 Answers 3

10

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())); 
Sign up to request clarification or add additional context in comments.

Comments

4

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())); 

Comments

2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.