字符串拼接null值问题

首先先看一个字符串拼接的例子:

public static void main(String[] args) {
        String testStr = null + "test";
        System.out.println(testStr);
        
    }

这个结果可能又可能与大家想的不同:

 其实出现这种情况的原因就是String.valueOf方法将null值会转变为"null"进行拼接,比较坑(testStr = testStr+"test"; 等价于 testStr = String.valueOf(testStr)+"test";)

public static String valueOf(Object obj) {
        return (obj == null) ? "null" : obj.toString();
    }

  

其实这种情况的解决办法有很多,下面我列举2个:

1、if判断

public static void main(String[] args) {
        String testStr = null;
        testStr = testStr == null? "test" : testStr + "test";;
        System.out.println(testStr);
    }

  

2、java 8 的Option.ofNullable()方法

public static void main(String[] args) {
        String testStr = null;
        testStr = Optional.ofNullable(testStr).orElse("") + "test";
        System.out.println(testStr);
    }

  

其他方法也有,基本都是先进行判空然后再进行拼接,不过大佬们若有好的方法可以留下评论,供类似我这种小菜学习!!

  

原文地址:https://www.cnblogs.com/Duancf/p/15217933.html