Amazon Cyber Monday deals See deals →ad

Mets Minor League Blog

Music theory, instruments and musicians

Mets Minor League Blog

Music theory, instruments and musicians

Long Value Compare in Java: Safe Ways to Compare Values

To compare primitive long values in Java, use ==, <, or > for direct tests, and Long.compare(a, b) when you need an ordering result. For boxed Long objects, use equals for value equality or compareTo for ordering; do not use == to test whether two objects contain the same number.

What “long value compare” means

Java has both the primitive type long and the reference type Long, which wraps a primitive value. The word “compare” can mean either checking whether two values are equal or deciding which one comes first in an ordering. Choosing the right operation depends on which type you have and what result the surrounding code expects.

A primitive long is a signed 64-bit integer. Its range is from -9,223,372,036,854,775,808 through 9,223,372,036,854,775,807. Ordinary relational operators treat it as signed: negative values are less than zero, and zero is less than positive values. A Long object stores a value in that same range, but it also has object identity and can be null. Those reference-type features account for many comparison bugs.

Compare primitive long values with operators

For a simple condition, operators are the clearest option. They compare the numeric values directly and return a boolean:

long first = 12L;
long second = 30L;

boolean same = first == second;
boolean before = first < second;
boolean after = first > second;

Use == when equality is all you need, and < or > when checking a threshold or ordering. The inclusive forms <= and >= include equality. For example, timestamp >= deadline directly expresses that a timestamp is at or beyond a deadline.

When one operand is an int and the other is a long, Java widens the int to long for the comparison. Every possible int value is representable as a long, so this comparison does not lose integer precision. By contrast, comparing a long with a float or double can involve conversion to a floating-point type, which cannot represent every large integer exactly. Keep integer quantities as integers when exact comparison matters.

Use Long.compare for an ordering result

Long.compare(a, b) compares two primitive values and returns an int: a negative number if a is less than b, zero if they are equal, or a positive number if a is greater. The exact negative or positive number is not part of the useful contract; test its sign or compare it with zero.

int result = Long.compare(a, b);

if (result < 0) {
    System.out.println("a comes first");
} else if (result == 0) {
    System.out.println("the values are equal");
} else {
    System.out.println("b comes first");
}

This method is especially useful when an API asks for an ordering result, such as a comparator. It is also clearer and safer than subtracting the values. A common but incorrect shortcut is (int) (a - b). Subtraction can overflow for extreme values, and converting the result to int can discard significant bits. Either problem can produce the wrong ordering. Long.compare handles the full range correctly.

Compare boxed Long objects

For two non-null Long references, call equals to test whether they hold the same numeric value. Call compareTo to order them:

Long first = 12L;
Long second = 30L;

boolean same = first.equals(second);
int order = first.compareTo(second);

Long.equals returns true only when the other object is also a Long with the same long value. It does not treat a different wrapper type as equal: a Long containing 12 is not equal to an Integer containing 12. For a null-safe equality check, use Objects.equals(first, second). It returns true when both references are null, false when just one is null, and otherwise delegates to value equality.

Do not use first == second to test equality between two Long references. In that expression Java checks whether both references point to the same object, not whether their values match. Some small boxed values may appear to work because boxing can reuse cached objects, but code must not depend on object identity for numeric equality. Prefer equals, Objects.equals, or explicit unboxing.

Autoboxing, unboxing, and null values

Java can automatically convert between long and Long. This is convenient, but it can obscure what a comparison actually does. If at least one operand of == is primitive, a Long operand is unboxed and the numeric values are compared. Thus boxed == 12L compares the wrapped value when boxed is non-null. If both operands are Long references, == checks identity instead.

Unboxing a null reference throws NullPointerException. That applies not only to a comparison such as boxed < limit, but also to calls such as Long.compare(boxed, other) and boxed.compareTo(other), because each needs a primitive value. Decide how null should be handled before comparing nullable values. For example, check for null explicitly, use Objects.equals for equality, or use a null-aware comparator where sorting requires one.

For a list that may contain nulls, Java comparators provide explicit policies. Comparator.nullsFirst(Long::compareTo) sorts null before non-null values; Comparator.nullsLast(Long::compareTo) puts null after them. These options make the intended rule visible instead of allowing an unexpected unboxing exception during a sort.

Compare and sort long values in collections

When implementing a comparator for primitive fields, use Long.compare rather than subtraction. The Comparator.comparingLong helper is often even more readable for objects that expose a long-valued key:

List<Record> records = ...;
records.sort(Comparator.comparingLong(Record::getId));

This orders records by their ID in ascending signed order. To reverse the order, use Comparator.comparingLong(Record::getId).reversed(). For multiple keys, chain another comparator with thenComparingLong. These helpers avoid writing a custom comparator for common cases and compare the extracted primitive key without converting it to an object for each comparison.

For a collection of boxed Long values, the natural order is signed numeric order. A sorted set or map using the natural order therefore places negative values before zero and positive values. If the collection can contain nulls, provide a null-aware comparator rather than relying on natural ordering alone. Also ensure a custom comparator is consistent with the equality behavior expected by the collection; sorted sets, for example, treat elements that compare as zero as equivalent for placement purposes.

Signed and unsigned comparisons

Most Java code should use signed comparison. Java’s primitive long is signed, and operators, Long.compare, and Long.compareTo all follow signed numeric order. Java also provides Long.compareUnsigned(a, b) for cases where the 64 bits represent an unsigned integer rather than a signed quantity.

An unsigned 64-bit value ranges from zero through 18,446,744,073,709,551,615, which is larger than the positive range of a signed long. Java still stores the bits in a long; unsigned comparison changes how those bits are interpreted for ordering. For example, -1L has all bits set. As a signed value it is less than zero, but as an unsigned 64-bit value it represents the largest possible value, so Long.compareUnsigned(-1L, 1L) reports that the first value is greater.

Unsigned operations are useful when interoperating with formats, protocols, or algorithms that define unsigned 64-bit quantities. Use the related unsigned parsing and formatting methods, such as Long.parseUnsignedLong and Long.toUnsignedString, when the text representation must follow unsigned rules too. Do not switch to unsigned comparison merely because a value is negative; first confirm that the data specification actually defines it as unsigned.

How to choose the right comparison

A practical rule is to match the operation to the type and purpose. For two primitives, ordinary operators make a direct condition easy to read. For an ordering result, use Long.compare. For two non-null wrapper objects, use equals for equality and compareTo for ordering. For nullable references, handle null explicitly or choose a null-aware comparator.

  • Need a true-or-false numeric test? Use a == b, a < b, or another relational operator on primitive values.
  • Need a comparator result? Use Long.compare(a, b); avoid subtraction.
  • Need value equality for boxed objects? Use equals or Objects.equals if either may be null.
  • Need to sort objects by a long field? Use Comparator.comparingLong.
  • Need unsigned ordering? Use Long.compareUnsigned only when the data is defined as unsigned.

Keeping these choices consistent makes code easier to review. In particular, a condition should not be made harder to understand by calling a comparison method when a relational operator says exactly what is meant, and an ordering method should not be replaced by arithmetic that can overflow.

Frequently Asked Questions

Can I compare two long values with == in Java?
Yes. If both values are primitive longs, == tests numeric equality. If both are Long references, it tests whether they refer to the same object. Use equals or Objects.equals for boxed value equality.

What does Long.compare return?
It returns a negative integer when the first long is smaller, zero when the values are equal, and a positive integer when the first is larger. Check whether the result is below, equal to, or above zero rather than relying on a particular nonzero value.

Is Long.compare safer than subtracting two longs?
Yes. Subtracting can overflow, and casting the difference to int can lose information. Long.compare determines the ordering without those problems.

Can Long.compare throw a NullPointerException?
The method takes primitive long parameters. Passing a Long reference causes unboxing, so a null argument throws NullPointerException. Check for null or use a comparator with an explicit null policy.

What is the difference between compareTo and equals for Long?
equals answers whether another object is a Long with the same value. compareTo gives an ordering result: negative, zero, or positive. For non-null Long values, a result of zero corresponds to equal numeric values.

Long Value Compare in Java: Safe Ways to Compare Values
Scroll to top