连接字符串中的条件运算符 [英] Conditional operator in concatenated string

查看:120
本文介绍了连接字符串中的条件运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么下面的程序会抛出一个NPE

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

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.

这篇关于连接字符串中的条件运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆