CKTIS / Java
Objects.equals: comparing titles that may be null
Compare titles safely when either may be missing, then enforce a separate non-null requirement when generating a label.
Version: Java SE 21
Syntax
import java.util.Objects;
// Declaration in java.util.Objects (Java SE 21):
public static boolean equals(Object a, Object b)
// Use in an expression or statement:
boolean equal = Objects.equals(a, b);Objects.equals(a, b) is a static method in java.util.Objects that takes two Object arguments and returns a boolean. Two null arguments compare equal. Exactly one null compares unequal when equals follows its contract. If both references point to the same object, the result is true; the JDK 21 implementation returns it without calling a.equals(b). For two distinct non-null references, the result comes from a.equals(b).
For String objects, equality means the same sequence of characters. By contrast, == on references tests whether both refer to the same object or both are null. Objects.equals does not compare array elements; use Objects.deepEquals for deep array comparison. It does not fix a broken equals implementation or catch exceptions thrown by it.
Two missing titles can compare equal, but a true result does not prove a title is present. If a label requires a title, use Objects.requireNonNull(title, "title is required") before calling strip(). A missing title then triggers a NullPointerException with that message. This check does not reject empty or whitespace-only strings.
Examples
import java.util.Objects;
public class Main {
private static String label(String title) {
return "Title: " + Objects.requireNonNull(title, "title is required").strip();
}
public static void main(String[] args) {
String title = "Atlas";
String sameText = new String(title); // Deliberately distinct reference.
String missing = null;
System.out.println(Objects.equals(missing, null));
System.out.println(Objects.equals(title, missing));
System.out.println(Objects.equals(title, sameText));
System.out.println(title == sameText);
System.out.println(label(title));
try {
System.out.println(label(missing));
} catch (NullPointerException e) {
System.out.println(e.getMessage());
}
}
}Result
true false true false Title: Atlas title is required
Two separate `String` objects containing `Atlas` compare equal with `Objects.equals` but not with `==`. Two missing titles compare equal, yet `label` rejects a missing title; the example catches the exception and prints its message.
Related lessons
- Java · Lesson 18 · Advanced · Version: 2
Sources
- Java SE 21 API — Objects.equals(Object, Object)
- Java SE 21 API — Object.equals(Object)
- Java SE 21 API — String.equals(Object)
- Java Language Specification, Java SE 21 — §15.21.3 Reference Equality Operators == and !=
- Java SE 21 API — Objects.deepEquals(Object, Object)
- Java SE 21 API — Objects.requireNonNull(T, String)