Conditional operator in concatenated string

后端 未结 4 1862
天命终不由人
天命终不由人 2020-12-11 01:35

I\'d like know why the following program throws a NPE

public static void main(String[] args) {
    Integer testInteger = null;
    String test = \"test\" + t         


        
相关标签:
4条回答
  • 2020-12-11 01:51

    I believe you need to add the parenthesis. Here is a working example which produces "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;
    }
    
    0 讨论(0)
  • 2020-12-11 01:54

    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.

    0 讨论(0)
  • 2020-12-11 02:11

    Without the brackets it's doing this effectively: String test = ("test" + testInteger) == null ? "(null)" : testInteger.toString(); Which results in an NPE.

    0 讨论(0)
  • 2020-12-11 02:12

    Because it's evaluated as "test" + testInteger (which is "testnull", and therefore NOT null), meaning your testInteger == null test will never return true.

    0 讨论(0)
提交回复
热议问题