Comparing Long Values in Java

1. Overview

In this short tutorial, we’ll discuss different ways to compare two Long instances. We emphasize the problems that arise when using the reference comparison operator (==).

2. Problem Using Reference Comparison

Long is a wrapper class for the primitive type long. Since they are objects and not primitive values, we need to compare the content of Long instances using .equals() instead of the reference comparison operator (==).

In some cases, we may get the idea that == is okay, but looks are deceiving. Consider that we can use == with low numbers:

Long l1 = 127L;
Long l2 = 127L;

assertThat(l1 == l2).isTrue();

but not with larger numbers. We would end up having issues if values are out of the range -128 to 127, having a completely different and unexpected result:

Long l1 = 128L;
Long l2 = 128L;

assertThat(l1 == l2).isFalse();

This is because Java maintains a constant pool for instances of Long between -128 and 127.

This optimization, though, does not give us a license to use ==. In the general case, two boxed instances having the same primitive value don’t yield the same object reference.

3. Using .equals()

One of the solutions is to use the .equals()This will evaluate the content (and not the reference) of both objects:

Long l1 = 128L;
Long l2 = 128L;

assertThat(l1.equals(l2)).isTrue();

4. Objects.equals()

The problem with using equals() is that we need to be cautious not to call it on the null reference.

Luckily, there’s a null-safe utility method we can use – Objects.equals().

Let’s see how it works in practice:

Long l1 = null;
Long l2 = 128L;

assertThatCode(() -> Objects.equals(l1, l2)).doesNotThrowAnyException();

As we can see, we don’t need to bother if any of the Longs we want to compare is null.

Under the hood, Objects.equals() first uses the == operator for the comparison, and if that fails it uses a standard equals().

5. Unboxing Long Values

5.1. Using the .longValue() Method

Next, let’s use the “==” comparison operator, but in a safe way. The class Number has a method .longValue() which unwraps the primitive long value:

Long l1 = 128L;
Long l2 = 128L;

assertThat(l1.longValue() == l2.longValue()).isTrue();

5.2. Casting to Primitive Values

A different way to unbox a Long is by casting the objects to primitive types. Therefore, we’ll extract the primitive value and then we can proceed to use the comparison operator:

Long l1 = 128L;
Long l2 = 128L;

assertThat((long) l1 == (long) l2).isTrue();

Note that, for the .longValue() method or using casting, we should check if the object is null. We could have a NullPointerException if the object is null.

6. Conclusion

In this short tutorial, we have explored different options on how to compare Long objects. We have analyzed the differences when comparing references to objects or content.

As always, the full source code of the article is available over on GitHub.

Related posts:

Sử dụng Fork/Join Framework với ForkJoinPool trong Java
Java Program to Compute the Area of a Triangle Using Determinants
Tránh lỗi ConcurrentModificationException trong Java như thế nào?
Java Program to Remove the Edges in a Given Cyclic Graph such that its Linear Extension can be Found
Dockerizing a Spring Boot Application
A Guide to WatchService in Java NIO2
Java Program to Perform Optimal Paranthesization Using Dynamic Programming
LinkedHashSet trong java
Create Java Applet to Simulate Any Sorting Technique
Implementing a Binary Tree in Java
Guide to BufferedReader
Java Program to Implement Cubic convergence 1/pi Algorithm
Java Program to Check Whether Graph is DAG
How to Kill a Java Thread
Serialization và Deserialization trong java
Use Liquibase to Safely Evolve Your Database Schema
JUnit5 Programmatic Extension Registration with @RegisterExtension
Giới thiệu JDBC Connection Pool
Spring Data Java 8 Support
How to Change the Default Port in Spring Boot
Java Program to Implement Queue using Two Stacks
Java – Write to File
Spring Security OAuth2 – Simple Token Revocation
Java Program to Implement Sieve Of Atkin
REST Web service: Tạo ứng dụng Java RESTful Client với Jersey Client 2.x
Java Program to Implement the Program Used in grep/egrep/fgrep
Java Program to Implement Suffix Tree
Ép kiểu trong Java (Type casting)
Từ khóa static và final trong java
Inject Parameters into JUnit Jupiter Unit Tests
Java Program to Implement Segment Tree
An Intro to Spring Cloud Contract