Sub topic 16
Comparison and equality
This chapter covers how Apex decides whether two values are equal or which one is larger. It assumes you can declare variables of the primitive and collection types and that you know what null means in Apex. Apex differs from Java and JavaScript here in several ways that cause real bugs.
The comparison operators
Apex has two groups of comparison operators: equality and relational.
| Operator | Meaning | Notes |
|---|---|---|
| `==` | Equal in value | Case-insensitive for `String`. Compares contents for collections and SObjects. |
| `!=` | Not equal in value | The negation of `==`. |
| `===` | Exact equality | For objects, true only when both sides are the same instance in memory. |
| `!==` | Not exactly equal | The negation of `===`. |
| `<`, `<=`, `>`, `>=` | Ordering | Defined for numbers, dates, times, strings, and Ids. |
Every comparison returns a Boolean that is either true or false. Apex has no three-valued logic, so a comparison never evaluates to null.
Strings: == ignores case
For strings, == is case-insensitive. The equals method is case-sensitive.
String a = 'apex';
String b = 'APEX';
System.debug(a == b);
System.debug(a.equals(b));
System.debug(a.equalsIgnoreCase(b));
System.debug(a.compareTo(b) == 0);The first line prints true and the other three print false, true, and false. compareTo returns a negative number, zero, or a positive number, and it is case-sensitive.
The relational operators on strings are also case-insensitive. If you need a case-sensitive order, use compareTo.
Numbers and widening
When the two sides have different numeric types, Apex widens the narrower one before comparing. An Integer compared with a Decimal is compared by numeric value.
Integer i = 5;
Long l = 5L;
Decimal d = 5.0;
System.debug(i == l);
System.debug(l == d);
System.debug(i < 6.5);All three lines print true. Comparing Double values for exact equality is risky because binary floating point cannot represent values like 0.1 exactly. Use Decimal for money and other exact values.
Null in comparisons
null == null is true. A non-null value is never equal to null.
String note;
Integer total = null;
System.debug(note == null);
System.debug(total == null);
System.debug(total != 5);This prints true, true, and true. Equality tests with null are safe. Do not depend on the result of a relational comparison such as total < 5 when total is null. Check for null first, or use ?? to supply a default (covered in a later chapter).
Calling a method on a null reference, such as note.equals('x'), throws a NullPointerException. The == operator does not, so note == 'x' is safe when note is null. A common defensive pattern puts the known non-null value on the left: 'x'.equals(note).
Collections and SObjects compare by contents
In Java, == on two objects compares references. In Apex, == compares values for built-in container types.
List<Integer> one = new List<Integer>{ 1, 2, 3 };
List<Integer> two = new List<Integer>{ 1, 2, 3 };
List<Integer> reordered = new List<Integer>{ 3, 2, 1 };
System.debug(one == two);
System.debug(one == reordered);
System.debug(one === two);
Set<String> s1 = new Set<String>{ 'a', 'b' };
Set<String> s2 = new Set<String>{ 'b', 'a' };
System.debug(s1 == s2);
Account x = new Account(Name = 'Acme');
Account y = new Account(Name = 'Acme');
System.debug(x == y);
System.debug(x === y);The output is true, false, false, true, true, false. These are the rules:
- Two lists are equal when they have the same size and equal elements in the same order.
- Two sets are equal when they contain the same elements. Order does not matter.
- Two maps are equal when they have the same keys and equal values for each key.
- Two SObjects are equal when they have the same type and the same field values. Two records with the same data can be
==even though they are different instances. ===is true only when both variables point at the same instance.
Ids are compared by value, and a 15-character Id equals its 18-character form with ==.
Your own classes
For a class you write, == compares references unless the class defines equals and hashCode. If you define them, == calls equals. Sets and map keys use the same pair of methods.
public class Money {
public Decimal amount;
public String currencyCode;
public Money(Decimal amount, String currencyCode) {
this.amount = amount;
this.currencyCode = currencyCode;
}
public Boolean equals(Object other) {
if (other == null || !(other instanceof Money)) {
return false;
}
Money m = (Money) other;
return amount == m.amount && currencyCode == m.currencyCode;
}
public Integer hashCode() {
return System.hashCode(amount) * 31 + System.hashCode(currencyCode);
}
}With this class saved, new Money(5, 'USD') == new Money(5, 'USD') is true, and === on the same two expressions is false. Whenever you override equals, override hashCode so that equal objects produce equal hash codes.
Enums and other types
Enum values are compared with ==. Dates, datetimes, and times compare by their value, so Date.newInstance(2026, 11, 30) == Date.today() is a value test, not a reference test.
public enum Season { WINTER, SPRING, SUMMER, FALL }
Season current = Season.SPRING;
System.debug(current == Season.SPRING);Choosing an operator
Common mistakes
- Using
==for a case-sensitive check, such as a code or token. Useequals. - Using
===on two SObjects and expecting a data comparison. It tests identity. - Expecting
Map<String, ...>.getto ignore case because==does. - Overriding
equalswithouthashCode, which breaks set and map behavior. - Comparing
Doubleresults for exact equality after arithmetic.
Exercise
Given String a = 'Ok'; String b = 'OK'; List<String> l1 = new List<String>{ a }; List<String> l2 = new List<String>{ b };, what do a == b, a.equals(b), l1 == l2, and l1 === l2 evaluate to?
Show answer
a == b is true because string == ignores case. a.equals(b) is false because equals is case-sensitive. l1 == l2 is true because list equality compares elements with the same == rule, which ignores case for strings. l1 === l2 is false because they are two different list instances.
Exercise
A Map<String, Integer> holds the key 'Pens'. Why does stock.get('pens') return null, and how do you make lookups ignore case?
Show answer
Map keys are matched case-sensitively, even though == on strings is not. To ignore case, store and look up keys in one normalized form, for example stock.put(key.toLowerCase(), value) and stock.get(key.toLowerCase()).