[英]Conditional operator in concatenated string
我想知道為什么以下程序會拋出一個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();
這導致了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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.