使用equals()小技巧

使用equals()小技巧

经常需要比较两个字符串是否相等,如果当String对象为null,却使用equals()方法来比较时,会报错,抛出NullPointerException。或者要多加一个步骤:判断str1 不为空

public static void main(String[] args) {
        String str1 = null;
        //比较两个字符串是否相等
        if (str1 != null){       #要添加判断:str1 不为空,否则会报错NullPointerException
            boolean isEqual = "hello".equals(str1);
            System.out.println(isEqual);
        }
    }

其实可以把字符串放在前面,这样就算str1为空,那么也不会报错,只会判断为不相等

    public static void main(String[] args) {
        String str1 = null;
        //比较两个字符串是否相等
        boolean isEqual = "hello".equals(str1);
        System.out.println(isEqual);  //输出false
    }
原文地址:https://www.cnblogs.com/eathertan/p/12517836.html