What is NumberUtils.compare() in Java?

Overview

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

How to import NumberUtils

The definition of NumberUtils 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 NumberUtils class as follows:


import org.apache.commons.lang3.math.NumberUtils;

Syntax


public static int compare(final int x, final int y)

Parameters

  • final int x: This is the first number.

  • final int y: This is the second number.

Return value

  • The method returns zero if both the numbers are equal.

  • The method returns -1 if the first number is less than the second number.

  • The method returns 1 if the first number is greater than the second number.

Overloaded methods

  • public static int compare(final long x, final long y)
  • public static int compare(final short x, final short y)
  • public static int compare(final byte x, final byte y)

Code

import org.apache.commons.lang3.math.NumberUtils;
public class Main{
public static void main(String[] args){
// Example 1
int x = -9;
int y = 5;
System.out.printf("The output of NumberUtils.compare(%s, %s) is %s", x, y, NumberUtils.compare(x, y));
System.out.println();
// Example 2
x = 5;
y = -9;
System.out.printf("The output of NumberUtils.compare(%s, %s) is %s", x, y, NumberUtils.compare(x, y));
System.out.println();
// Example 3
x = 5;
y = 5;
System.out.printf("The output of NumberUtils.compare(%s, %s) is %s", x, y, NumberUtils.compare(x, y));
}
}

Explanation

Example 1

  • x = -9
  • y = 5

The method returns -1 because x < y.

Example 2

  • x = 5
  • y = -9

The method returns 1 because x > y.

Example 3

  • x = 5
  • y = 5

The method returns 0 because x == y.

Output

The output of the code will be as follows:


The output of NumberUtils.compare(-9, 5) is -1
The output of NumberUtils.compare(5, -9) is 1
The output of NumberUtils.compare(5, 5) is 0

Free Resources

Attributions:
  1. undefined by undefined