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

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

提交回复
热议问题