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.
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.
Without the brackets it's doing this effectively:
String test = ("test" + testInteger) == null ? "(null)" : testInteger.toString();
Which results in an NPE.
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