Java.lang Package Classes

Java Integer - compare() Method

The 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)).


public static int compare(int x,
                          int y)


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.




In the example below, the 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: " + 
              , val2)); 
    System.out.println("comparing val1 and val3: " + 
              , val3)); 
    System.out.println("comparing val3 and val1: " + 
              , 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