Java.lang Package Classes

Java Integer - compare() Method



The java.lang.Integer.compare() method is used to compare two int values numerically. The value returned is identical to what would be returned by: Integer.valueOf(x).compareTo(Integer.valueOf(y)).

Syntax

public static int compare(int x,
                          int y)

Parameters

x Specify the first int to compare.
y Specify the second int to compare.

Return Value

Returns the value 0 if x == y; a value less than 0 if x < y; and a value greater than 0 if x > y.

Exception

NA.

Example:

In the example below, the java.lang.Integer.compare() method is used to compare given int values.

import java.lang.*;

public class MyClass {
  public static void main(String[] args) {
    
    //creating int values
    int val1 = 5;
    int val2 = 5;
    int val3 = -5;

    //comparing int values 
    System.out.println("comparing val1 and val2: " + 
                        Integer.compare(val1, val2)); 
    System.out.println("comparing val1 and val3: " + 
                        Integer.compare(val1, val3)); 
    System.out.println("comparing val3 and val1: " + 
                        Integer.compare(val3, val1));    
  }
}

The output of the above code will be:

comparing val1 and val2: 0
comparing val1 and val3: 1
comparing val3 and val1: -1

❮ Java.lang - Integer