连接字符串中的条件运算符
我想知道为什么以下程序会抛出一个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()); }
没有。 这肯定是一个优先考虑的问题,我很好奇连接是如何工作的。
这是理解运算符优先级的重要性的一个示例。
你需要括号,否则它被解释如下:
String test = ("test" + testInteger) == null ? "(null)" : testInteger.toString();
请参阅此处以获取运算符及其优先级的列表。 另请注意该页面顶部的警告:
注意:甚至可能出现混淆时使用明确的括号。
没有括号,它有效地做到了这一点: String test = ("test" + testInteger) == null ? "(null)" : testInteger.toString();
String test = ("test" + testInteger) == null ? "(null)" : testInteger.toString();
这导致了NPE。
因为它被评估为"test" + testInteger
(它是"testnull"
,因此"testnull"
null),这意味着你的testInteger == null
测试永远不会返回true。
我相信你需要添加括号。 这是一个生成“ http:// localhost:8080 / catalog / rest ”的工作示例
public static String getServiceBaseURL(String protocol, int port, String hostUrl, String baseUrl) { return protocol + "://" + hostUrl + ((port == 80 || port == 443) ? "" : ":" + port) + baseUrl; }