Java Integer compare() method


The compare() method is used to compare two integer values numerically. The syntax is −

int compare(int val1,int val2)  

Above, a and b are the two integer values to be compared. If the return value is -1, therefore val1 is less than val2. Return value is 1, when val1 == val 2. The return value is 1, when val1 is greater than val2.

At first, declare int values to be compared −

int val1 = 200;
int val2 = 250;
int val3 = 200;

Now, compare the values −

System.out.println(Integer.compare(val1, val2));
System.out.println(Integer.compare(val1, val3));

Following is an example to implement the compare() method in Java −

Example

public class Main {
   public static void main(String[] args) {
      int val1 = 200;
      int val2 = 250;
      int val3 = 200;
      System.out.println(Integer.compare(val1, val2));
      System.out.println(Integer.compare(val1, val3));
   }
}

Output

-1
0

Updated on: 20-Sep-2019

504 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements