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

后端 未结 9 1768
别那么骄傲
别那么骄傲 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:23

    Initializing a null String with "" should work.

    0 讨论(0)
  • 2021-02-04 06:28

    concate() method creates new String() object under the hood.

    where as + combines\ concatenates values by using toString() method. That's why when we use + it continents "somevalue".append(null).toString().

    for reference see this question.

    0 讨论(0)
  • 2021-02-04 06:32

    If you see in java.lang.String source, and use null as parameter. NPE is thrown in first line in length() method.

    public String concat(String str) {
        int otherLen = str.length();//This is where NullPointerException is thrown
        if (otherLen == 0) {
            return this;
        }
        getChars(0, count, buf, 0);
        str.getChars(0, otherLen, buf, count);
        return new String(0, count + otherLen, buf);
    }
    
    0 讨论(0)
  • 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);
        }
    
    0 讨论(0)
  • 2021-02-04 06:36

    Actual implementation of concate method is like this . this method need an object of type String as a parameter and if argument is null then it throws Null Pointer Exp.

    public String concat(String paramString)
      {
        int i = paramString.length();
        if (i == 0) {
          return this;
        }
        int j = this.value.length;
        char[] arrayOfChar = Arrays.copyOf(this.value, j + i);
        paramString.getChars(arrayOfChar, j);
        return new String(arrayOfChar, true);
      }
    
    0 讨论(0)
  • 2021-02-04 06:45

    @Blip : 1) null + "ABC"

    Straight forward answer to your question is + operator in java uses StringBuilder.append method to concat the strings.

    And StringBuilder.append() method treats null object as "null" String. Hence null + "ABC" won't give Null Pointer exception but rather prints nullABC.

    2) String.concat()

    And yes, there is no null check before string.length() method in concat() function of String class. Hence it is throwing null pointer exception.

    Hope this answers your question.

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