113
4-4. Comparing int Values
Problem
You need to compare two or more int values.
Solution 1
Use the comparison operators to compare integer values against one another. In the
following example, three int values are
compared against each other, demonstrating
various comparison operators.
public static void compareIntegers(){
int int1 = 1;
int int2 = 10;
int int3 = -5;
System.out.println(int1 == int2); // Result: false
System.out.println(int3 == int1); // Result: false
System.out.println(int1 == int1); // Result: true
System.out.println(int1 > int3); // Result: true
System.out.println(int2 < int3); // Result: false
}
The main class is:
public static void main(String[] args){
compareIntegers();
}
As you can see, comparison operators generate a boolean result.
Solution 2
Use the Integer.compare(int,int) method to compare two int values numerically. The
following lines could compare the same int values declared in the first solution.
System.out.println("Compare method -> int3 and int1:
" + Integer.compare(int3, int1));
// Result -1
Chapter 4 Numbers aNd dates
114
System.out.println("Compare method -> int2 and int1:
" + Integer.compare(int2, int1));
// Result 1
How It Works
Perhaps the most used numeric comparisons are against two or more int values.
The Java language makes it easy to compare an int using the comparison operators
(see
Table
4-1
).
Do'stlaringiz bilan baham: