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

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

    The String class holds an array (probably an ArrayList) of characters. When you call .concat() it goes through and adds every character from the second string to the first.

    If the first String is null, there is nothing to add to, causing a NullPointer Exception. Try initializing Strings with "".

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

    String.concat() need an object of type String as a parameter.

    There is no type which null is an instanceof. Refer JLS:

    15.20.2 Type Comparison Operator instanceof

    RelationalExpression: RelationalExpression instanceof ReferenceType At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast to the ReferenceType without raising a ClassCastException. Otherwise the result is false.

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

    Case 1:

     System.out.println(strNull+str);  // will not give you exception
    

    From the docs(String conversion)

    If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).

    Otherwise, the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments; but if the result of invoking the toString method is null, then the string "null" is used instead.

    Case 2:

    str.concat(strNull);  //NullPointer exception
    

    If you see the source of concat(String str) it uses str.length(); so it would be like null.length() giving you a NullPointerException.

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