Java – conditional operator in consecutive strings

I wonder why the following program throws an NPE

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

And this

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

No, This is certainly a priority issue, and I'm curious about how connections work

Solution

This is an example of understanding the importance of operator precedence

You need parentheses, otherwise it is explained as follows:

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

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

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>