Search code examples
javaequalsstrong-typing

What's the difference between "Foo".equals(maybeFoo) and maybeFoo==null?false:maybeFoo.equals("Foo")?


I'm facing a question to write a piece of java code like:

boolean isFoo(String maybeFoo){
    //Return true if maybeFoo is equal to "Foo"
    //Don't throw any exceptions.
}

I have two choices:

1. return "Foo".equals(maybeFoo);
2. return maybeFoo==null?false:maybeFoo.equals("Foo");

I choose the number 1, but I cannot give a reason why number 2 is wrong. I said to the interviewer, it's just my habit to deal with a strong type language. But he seems not satisfied.


Solution

  • The difference between those is exactly what you wrote in the 2 options

    "Foo".equals(maybeFoo);
    

    Is a most common implemented check because you don't have to take care about a null check... (even because is only one check more)

    On the other hand this

    maybeFoo.equals("Foo") 
    

    Will throw a NPE exception just because are calling methods on a null referenced object