Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional operator in concatenated string

Tags:

java

I'd like know why the following program throws a NPE

public static void main(String[] args) {
    Integer testInteger = null;
    String test = "test" + testInteger == null ? "(null)" : testInteger.toString();
}

while this

public static void main(String[] args) {
    Integer testInteger = null;
    String test = "test" + (testInteger == null ? "(null)" : testInteger.toString());
}

doesn't. It's certainly a priority problem and I'm curious how the concatenation works inside.

like image 479
peq Avatar asked Jul 27 '12 10:07

peq


2 Answers

This is an example of the importance of understanding operator precedence.

You need the parentheses otherwise it is interpreted as follows:

String test = ("test" + testInteger) == null ? "(null)" : testInteger.toString();

See here for a list of operators and their precedence. Also note the warning at the top of that page:

Note: Use explicit parentheses when there is even the possibility of confusion.

like image 122
Mark Byers Avatar answered Oct 19 '22 19:10

Mark Byers


Without the brackets it's doing this effectively: String test = ("test" + testInteger) == null ? "(null)" : testInteger.toString(); Which results in an NPE.

like image 6
meiamsome Avatar answered Oct 19 '22 19:10

meiamsome