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

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

提交回复
热议问题