Java Reference
In-Depth Information
Solution #2
Use the Integer.compare(int,int) method to compare two int values nu-
merically. The following lines could compare the same int values that were declared
in the first solution:
System.out.println("Compare method -> int3 and int1: "
+ Integer.compare(int3, int1));
// Result -1
System.out.println("Compare method -> int2 and int1: "
+ Integer.compare(int2, int1));
// Result 1
How It Works
Perhaps the most commonly used numeric comparisons are against two or more int
values. The Java language makes it very easy to compare an int using the comparison
operators (see Table 4-4 ).
Table 4-4 . Comparison Operators
Operator
Function
Equal to
==
Not equal to
!=
>
Greater than
Less than
<
Greater than or equal to
>=
Less than or equal to
<=
The second solution to this recipe demonstrates the integer compare() method
that was added to the language in Java 7. This static method accepts two int values
and compares them, returning a 1 if the first int is greater than the second, a 0 if the
two int values are equal, and a -1 if the first int value is less than the second. To
use the Integer.compare() method, pass two int values as demonstrated in the
following code:
 
 
Search WWH ::




Custom Search