Objects Utility Class in Java

Naveen AnamaneniUpdated · 4 min read

Many everyday object chores have a trap for null: a.equals(b) throws if a is null, obj.hashCode() throws, and a constructor that quietly stores a null causes a crash much later, far from the real mistake. java.util.Objects (with an s, not the Object class) is a small utility class of static methods that handle these chores null-safely in one line.

The Most Useful Methods

Helpers.java▶ Try it
import java.util.Objects;
 
public class Helpers {
    static final class Member {
        private final String name;
        private final String city;
 
        Member(String name, String city) {
            this.name = Objects.requireNonNull(name, "name must not be null");
            this.city = city;
        }
 
        @Override
        public boolean equals(Object o) {
            return o instanceof Member m
                && Objects.equals(name, m.name)
                && Objects.equals(city, m.city);
        }
 
        @Override
        public int hashCode() { return Objects.hash(name, city); }
 
        @Override
        public String toString() {
            return name + " from " + Objects.toString(city, "unknown city");
        }
    }
 
    public static void main(String[] args) {
        Member a = new Member("Srihitha", null);
        Member b = new Member("Srihitha", null);
        System.out.println(a);
        System.out.println(a.equals(b) + " " + (a.hashCode() == b.hashCode()));
 
        System.out.println(Objects.requireNonNullElse(null, "guest"));
        System.out.println(Objects.isNull(null) + " " + Objects.nonNull(a));
 
        try {
            new Member(null, "Hyderabad");
        } catch (NullPointerException e) {
            System.out.println("Rejected: " + e.getMessage());
        }
        try {
            Objects.checkIndex(5, 3);
        } catch (IndexOutOfBoundsException e) {
            System.out.println(e.getMessage());
        }
    }
}
Output
Srihitha from unknown city
true true
guest
true true
Rejected: name must not be null
Index 5 out of bounds for length 3

How it works

  1. Objects.requireNonNull(name, message) returns name if it isn't null, and throws NullPointerException with your message if it is. The constructor fails immediately, at the real mistake.
  2. Objects.equals(x, y) is true if both are null, false if only one is, and otherwise calls x.equals(y). Here city is null in both members, and nothing throws.
  3. Objects.hash(fields...) builds a hash code from several fields, null-safely.
  4. Objects.toString(obj, fallback) gives the fallback text for null.
  5. requireNonNullElse(value, default) returns a default for null.
  6. checkIndex(index, length) throws the standard bounds message for a bad index.

Quick Reference

MethodReturns
equals(a, b)true if both null or a.equals(b)
hash(values...)Combined hash code of the values
hashCode(o)o.hashCode(), or 0 for null
toString(o) / toString(o, fallback)"null" or the fallback for null
requireNonNull(o) / requireNonNull(o, message)o, or throws NullPointerException
requireNonNullElse(o, default)o, or the default if null
requireNonNullElseGet(o, supplier)o, or computes a default
isNull(o) / nonNull(o)Boolean checks, handy in streams (covered later in the course)
checkIndex(i, length)i, or throws IndexOutOfBoundsException
compare(a, b, comparator)0 if a == b, otherwise the comparator's result

Common Mistakes

Confusing Object and Objects. Object is the root class; Objects is a utility class in java.util.

Calling requireNonNull without using its result. It returns the value, so assign it in one line: this.name = Objects.requireNonNull(name).

Using Objects.hash on a hot path with many calls. It creates an array each time; for very frequently hashed objects, compute and cache the hash yourself.

Practice

  1. Easy: Write a Book class whose constructor rejects a null title with requireNonNull and a clear message.
  2. Harder: Write equals and hashCode for a Contact with name, phone and an optional email that may be null, using Objects.equals and Objects.hash.

Quick check: Objects class

4 questions
1What does Objects.equals(null, null) return?
2What does Objects.requireNonNull(x, "x needed") do if x is null?
3Which package is Objects in?
4What does Objects.hashCode(null) return?

Key Takeaways

Was this tutorial helpful?

Lesson 164 of 482