Search code examples
javastring-literals

Literal String methods versus Object methods


I have seen both versions, so I'm just wondering, is there any real difference between these two expressions? Which is the conventional way of writing it?

"hello".equals(myString)
 myString.equals("hello")

EDIT: This portion of my question makes it not a duplicate

Why is it good that "hello".equals(myString) doesn't throw an error? Wouldn't you want the caller to be responsible for using a null string? By this logic, wouldn't using myString.equals("hello") enforce cleaner code?


Solution

  • The best way is the first, because it cannot throw an exception.

    The second way throws a NullPointerException if myString is null.

    Why is it good that "hello".equals(myString) doesn't throw an error? Wouldn't you want the caller to be responsible for using a null string?

    You are correct that it is a good thing for programming errors to be detected as quickly as possible, so sometimes exceptions are a good thing. If myString should not be null, I would throw an exception for that explicitly, rather than relying on myString.equals("hello"); throwing an exception. For example

    public void someMethod(String myString) {
        if (myString == null)
            throw new NullPointerException();
        if ("hello".equals(myString))
            // do something
    }
    

    This code is completely equivalent to using if (myString.equals("hello")), but the intent is clearer, and there's no chance of another programmer coming along, not realising why you didn't put the literal first, and swapping it around.