0

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?

Michael
  • 2,673
  • 1
  • 16
  • 27

2 Answers2

3

Yes, the first version will never raise a NullPointerException, if myString is null it will return false.

Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
2

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.

Paul Boddington
  • 37,127
  • 10
  • 65
  • 116
  • [`Objects.requireNonNull(myString)`](http://docs.oracle.com/javase/7/docs/api/java/util/Objects.html#requireNonNull(T))… – Holger Sep 17 '15 at 13:20