Java null String equals result

 ̄綄美尐妖づ 提交于 2019-12-04 00:29:02

You cannot use the dereference (dot, '.') operator to access instance variables or call methods on an instance if that instance is null. Doing so will yield a NullPointerException.

It is common practice to use something you know to be non-null for string comparison. For example, "something".equals(stringThatMayBeNull).

Indeed, you cannot use the dot operator on a null variable to call a non static method.

Despite this, all depends on overriding the equals() method of the Object class. In the case of the String class, is:

public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = count;
        if (n == anotherString.count) {
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = offset;
            int j = anotherString.offset;
            while (n-- != 0) {
                if (v1[i++] != v2[j++])
                    return false;
            }
            return true;
        }
    }
    return false;
}

If you pass null as parameter, both "if" will fail, returning false;

An alternative for your case is to build a method for your requirements:

public static boolean myEquals(String s1, String s2){
    if(s1 == null)
        return s2 == null;
    return s1.equals(s2);
}

Use Objects.equals() to compare strings, or any other objects if you're using JDK 7 or later. It will handle nulls without throwing exceptions. See more here: how-do-i-compare-strings-in-java

That piece of code will throw a NullPointerException whenever string1 is null and you invoke equals on it, as is the case when a method is implicitly invoked on any null object.

To check if a string is null, use == rather than equals.

Although result1 and result3 will not be set due to NullPointerExceptions, result2 would be false (if you ran it outside the context of the other results).

You will get a NullPointerException in case 1 and case 3.

You cannot call any methods (like equals()) on a null object.

To prevent NPE while comparing Strings if at least one of them can be null, use StringUtils.equals method which is null-safe.

We cannot use dot operator with null since doing so will give NullPointerException. Therefore we can take advantage of try..catch block in our program. This is a very crude way of solving your problem, but you will get desired output.

try {
   result = string1.equals(string2);
} catch (NullPointerException ex) {
   result = string2 == null; //This code will be executed only when string 1 is null
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!