简体   繁体   中英

Do I need to check null and “” while comparing String in Java?

Suppose I have to compare two String s:

public String checkComaprision(String str) {
    if (!("Hello".equals(str))) {
        System.out.println("String didn't match to hello");
    }

    if ("".equals(str) || null == str || (!str.equals("Hello"))) {
        System.out.println("String didn't match to hello");
    }
}

Here I have used two methods of string comparison insider string. I have read at many places where we compare string with "" and with null before actual comparison. But I think the first case will work properly, and if so, then why should I check for null and blank?

Is there any case where the first comparison will fail? Which is the better approach?

There is no way that "Hello".equals(str)) would ever fail, a string literal simply can never be null . Same thing with "".equals(str) .

The method Objects.equals(Object, Object) automatically checks nulls first.


To answer your question, using if ("Hello".equals(str)) is just fine, but if you ever want to replace the string literal "Hello" by a variable, you should use Objects.equals(greeting, str) .
Checking for an empty string is absolutely unnecessary.

in your case the firs comparison will always work because we are sure that "hello" is never going to be null. Now if you want have a variable like this

private String s

then you want to compare with another throug a function like yours, you now need to make sure that s is different to null

s!=null

if not, you may have a NullPointerException

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM