Abichellam
Abichellam

Reputation: 509

Operator precedence - Arithmetic and Conditional operators

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

Upvotes: 5

Views: 210

Answers (3)

TheGraduateGuy
TheGraduateGuy

Reputation: 1520

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.

Upvotes: 2

Rohit Jain
Rohit Jain

Reputation: 213411

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

Upvotes: 10

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236170

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

Upvotes: 4

Related Questions