Java 17 Recipes


Table 4-1. Comparison Operators Operator Function


Download 3.2 Mb.
Pdf ko'rish
bet69/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   65   66   67   68   69   70   71   72   ...   245
Bog'liq
Java 17 Recipes

Table 4-1. 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 
added 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.
Integer.compare(int3, int1));
Integer.compare(int2, int1));
Just like in your math lessons at school, these comparison operators determine 
whether the first integer is equal to, greater than, or less than the second integer. 
Straightforward and easy to use, these comparison operators are most often seen within 
the context of an if statement.
Chapter 4 Numbers aNd dates


115
4-5. Comparing Floating-Point Numbers
 Problem
You need to compare two or more floating-point values in an application.
 Solution 1
Use the Float object’s compareTo() method to compare one float against another. The 
following example shows the compareTo() method in action.
public static void compareFloat(){
Float float1 = Float.valueOf ("9.675");
Float float2 = Float.valueOf ("7.3826");
Float float3 = Float.valueOf ("23467.373");
System.out.println(float1.compareTo(float3)); // Result: -1
System.out.println(float2.compareTo(float3)); // Result: -1
System.out.println(float1.compareTo(float1)); // Result: 0
System.out.println(float3.compareTo(float2)); // Result: 1
}
The main class is:
public static void main(String[] args){
compareFloat();
}
The result of calling the compareTo() method is an integer value. A negative result 
indicates that the first float is less than the float being compared against. A zero indicates 
that the two float values are equal. Lastly, a positive result indicates that the first float is 
greater than the float being compared against.
Chapter 4 Numbers aNd dates


116

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   65   66   67   68   69   70   71   72   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling