11

Is there any benefit to using val1.equals(val2) instead of val1 == val2 syntax?

I'm very conditioned to using ==, but was wondering if there was any specific benefit to using the .equals() syntax for any reason...

0
19

== actually has different behavior depending on the arguments.

For example, given two strings:

String h1 = 'Hello World';
String h2 = 'hello world';
System.debug(h1.equals(h2)); // false
System.debug(h1==h2); // true
System.debug(h1===h2); // false
System.debug(h1.equalsIgnoreCase(h2)); // true

In other cases, such as numbers, == operates the way you'd expect. It has to match exactly. For objects, == calls .equals, so there's no difference.

=== is basically comparing by memory addresses, while == is (usually) shorthand for .equals, except for strings, in which case is actually shorthand for .equalsIgnoreCase.

While you're more likely to use == than .equals in everyday scenarios, it doesn't hurt to know that behind the scenes, it's basically compiled into the same instructions, as long as you remember that strings are kind of magical and don't follow the rules that everything else does.

Also, comparable types will be automatically converted into types, allowing you to compare various types (e.g. numbers).

System.debug(1.0 == 1); // true
System.debug(1.0 == 1L); // true

This doesn't extend to date/date-time or other types, though, but there's functions to get just the date part of a date-time, etc.

Use .equals when comparing strings and you want to make sure people know it's case sensitive. Use == if you don't want case sensitivity (it's shorter than the verbose .equalsIgnoreCase, which as far as I'm concerned, has no practical use).

2
  • 5
    Note also that a.equals(b) will get a nullPointerException if a is null whereas a == b will not
    – cropredy
    Feb 7 '15 at 0:33
  • That's a great qualification @crop1645 ... that in and of itself is a reason to use == instead of .equals() for me... Feb 10 '15 at 22:19

Not the answer you're looking for? Browse other questions tagged or ask your own question.