StringBuilder append() and null values

后端 未结 8 924
借酒劲吻你
借酒劲吻你 2021-02-06 21:54

I have a list of Strings, and I want to concatenate them with spaces in between. So I\'m using StringBuilder. Now if any of the Strings ar

相关标签:
8条回答
  • 2021-02-06 22:48

    You can use commons-lang's StringUtils#defaultString():

    sb.append("Value: ").append(StringUtils.defaultString(myVar));
    
    0 讨论(0)
  • 2021-02-06 22:53

    You can do a check on the object before appending it:

    sb.append("Value: ");
    if (s != null) sb.append(s);
    System.out.println(sb);
    

    A key point to make is that null is not the same an an empty String. An empty String is still a String object with associated methods and fields associated with it, where a null pointer is not an object at all.

    From the documentation for StringBuilder's append method:

    The characters of the String argument are appended, in order, increasing the length of this sequence by the length of the argument. If str is null, then the four characters "null" are appended.

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