字符串拼接出现null的问题

  最近在开发的过程中遇到这样的问题,原因是在做一个需求的时候,要求将解密的号码和前缀进行拼接。一开始在这个拼接的过程中,没有考虑到数据校验的问题,因为有可能他的前缀或者其他需要拼接的字段在前端传递的过程中,可能是没有传过来。所以在拼接的时候可能会忽略一个问题,就是字符串拼接了null。

  下面看一下错误的拼接例子:

public class Demo {
    public static void main(String[] args) {

        String testOne = null;
        String testTwo = "test";

        String testThree = testTwo + testOne;
        System.out.println(testThree);

        String testFour = testOne + testTwo;
        System.out.println(testFour);

    }
}

  打印结果如下:

  很明显,这样的拼接结果是错误的。

  

  正确的例子如下:

public class Demo {
    public static void main(String[] args) {

        String testOne = null;
        String testTwo = "test";

        if(testOne == null){
            testOne = "";
        }
        if(testTwo == null){
            testTwo = "";
        }
        String testThree = testTwo + testOne;
        System.out.println(testThree);

    }
}

  在拼接字段,对需要拼接的字段先进行校验,如果是null的话,给它赋值成空串。

  打印结果如下:

  这样拼接的结果就不容易出错啦!

原文地址:https://www.cnblogs.com/lu97/p/14175931.html