Why String concatenate null with + operator and throws NullPointerException with concate() method

后端 未结 9 1772
别那么骄傲
别那么骄傲 2021-02-04 06:23

Here is my class, where i am concatenating two string. String concatenate with null using + operator execute smoothly but throws NullPointerException

9条回答
  •  迷失自我
    2021-02-04 06:35

    Because inside concat method in String class, length method is getting invoked on passed parameter , due to which NPE is thrown.

    public String concat(String str) {
            int otherLen = str.length();<------
            if (otherLen == 0) {
                return this;
            }
            int len = value.length;
            char buf[] = Arrays.copyOf(value, len + otherLen);
            str.getChars(buf, len);
            return new String(buf, true);
        }
    

提交回复
热议问题