3.4 Comparison Operators
Comparison operators are used to compare two operands. They are mainly used in the conditional expressions of conditional statements (such as if, while, etc.), and the result of the operation must always be one of the boolean values: true or false.
1. Relational Comparison Operators (<, >, <=, >=)
They compare whether two operands are greater or smaller. (Mainly used for numeric type variables; booleans cannot be compared for magnitude)
>: Returns true if the left side is greater than the right side.<: Returns true if the left side is smaller than the right side.>=: Returns true if the left side is greater than or equal to the right side.<=: Returns true if the left side is smaller than or equal to the right side.
int a = 10, b = 5;
System.out.println(a > b); // true
System.out.println(a <= b); // false
2. Equality Comparison Operators (==, !=)
They compare whether the values of two operands are identical or different. (Applicable to all data types)
==: Returns true if the values on the left and right sides are the same.!=: Returns true if the values on the left and right sides are different.
int i = 10;
int j = 10;
boolean result = (i == j); // The values of variables i and j are the same, so result is true
Caution: Comparing Strings (String)
When comparing Strings, you must use the .equals() method instead of ==.
Using == compares the memory addresses pointed to by the objects, rather than the internal value (Data) of the string, which can lead to unexpected results.
String str1 = new String("Hello");
String str2 = new String("Hello");
System.out.println(str1 == str2); // false (They point to different memory addresses)
System.out.println(str1.equals(str2)); // true (Their internal string values are identical)