Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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());
    }
}
like image 317
Abichellam Avatar asked Sep 05 '13 05:09

Abichellam


People also ask

What is the precedence of arithmetic operators?

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.

Which has highest precedence in arithmetic?

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.


3 Answers

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()));
like image 58
Rohit Jain Avatar answered Oct 16 '22 14:10

Rohit Jain


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()));
like image 4
Óscar López Avatar answered Oct 16 '22 15:10

Óscar López


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.

like image 2
TheGraduateGuy Avatar answered Oct 16 '22 14:10

TheGraduateGuy