What is ObjectUtils.compare() in Java?

compare() is a staticthe methods in Java that can be called without creating an object of the class. method of the ObjectUtils class that is used to compare two comparables.

Comparables are the objects whose classes implement the Comparable interface.

Paramters

The method optionally accepts a parameter called nullGreater. If true, then null is considered greater than a non null value. If false, then null is considered less than a non null value.

Return value

  • The method returns a negative value if the first object is less than the second one.
  • The method returns a positive value if the first object is greater than the second one.
  • The method returns zero if both the objects are equal.

How to import ObjectUtils

The definition of ObjectUtils can be found in the Apache Commons Lang package, which we can add to the Maven project by adding the following dependency to the pom.xml file:

<dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
</dependency>

For other versions of the commons-lang package, refer to the Maven Repository.

You can import the ObjectUtils class as follows:

import org.apache.commons.lang3.ObjectUtils;

Syntax

public static <T extends Comparable<? super T>> int compare(final T c1, final T c2, final boolean nullGreater)

Parameters

  • final T c1: The first object.
  • final T c2: The second object.
  • final boolean nullGreater: A Boolean flag indicating if null objects have to be treated as greater than or lesser than non null objects.

Return value

This method returns a positive value if c1 > c2, a negative value if c1 < c2, or zero if c1 = c2.

Code

import org.apache.commons.lang3.ObjectUtils;
public class Main{
public static void main(String[] args) {
// Example 1
String object1 = "hello";
String object2 = "hello";
System.out.printf("ObjectUtils.compare(%s, %s) = %s", object1, object2, ObjectUtils.compare(object1, object2));
System.out.println();
// Example 2
object1 = "";
object2 = "hello";
System.out.printf("ObjectUtils.compare(%s, %s) = %s", object1, object2, ObjectUtils.compare(object1, object2));
System.out.println();
// Example 3
object1 = "hello";
object2 = null;
System.out.printf("ObjectUtils.compare(%s, %s) = %s", object1, object2, ObjectUtils.compare(object1, object2));
System.out.println();
}
}

Output

The output of the code will be as follows:

ObjectUtils.compare(hello, hello) = 0
ObjectUtils.compare(, hello) = -5
ObjectUtils.compare(hello, null) = 1

Example 1

  • object1 = "hello"
  • object2 = "hello"

The method returns 0, as both the objects are equal.

Example 2

  • object1 = ""
  • object2 = "hello"

The method returns -5 as object2 > object1.

Example 3

  • object1 = "hello"
  • object2 = null

The method returns 1 as object1 > object2.

Free Resources