簡體   English   中英

連接字符串中的條件運算符

[英]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(); 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM