5

Suppose I have to compare two Strings:

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?

4
  • 5
    Answer is: Nope Commented Jan 6, 2017 at 12:29
  • 2
    The yoda notation is there to remove the null check. Commented Jan 6, 2017 at 12:30
  • If you would write str.equals("Hello"), then you have first to check that str is not null. But "Hello".equals(str) does not need previous checks. Commented Jan 6, 2017 at 12:31
  • ideone.com/wn0p7R - I would use this. Without extra parenthesis. Commented Jan 6, 2017 at 12:31

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I was going to suggest StringUtils.equals(str1, str2), but I didn't know about Objects.equals(str1, str2), thanks
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.