Index
Java Relational Operators
Relational operators are used to check the relationship between two operands and return a boole
value
Here, <
operator is the relational operator. It checks if a is less than b or not.
It returns either true
or false
.
Operator | Description | Example |
---|---|---|
== | Is Equal To | 3 == 5 returns false |
!= | Not Equal To | 3 != 5 returns true |
> | Greater Than | 3 > 5 returns false |
< | Less Than | 3 < 5 returns true |
>= | Greater Than or Equal To | 3 >= 5 returns false |
<= | Less Than or Equal To | 3 <= 5 returns true |
Relational Operators with Numbers
Relational operators can be used to compare numeric values:
Relational Operators with Characters
Relational operators can also be used to compare characters. Characters are internally represented as Unicode code points, so the comparison is based on their numeric values:
Relational Operators with Strings
Relational operators cannot be directly applied to strings as they are with numeric types. Instead, the compareTo()
or equals()
methods should be used to compare strings.
The compareTo()
method returns an integer value that indicates the relationship between the two strings:
- If
a.compareTo(b) > 0
, thena
is greater thanb
. - If
a.compareTo(b) < 0
, thena
is less thanb
. - If
a.compareTo(b) == 0
, thena
is equal tob
.
The equals()
method returns a boolean value that indicates the relationship between the two strings:
- If
a.equals(b) == True
, thena
is equal tob
. - If
a.equals(b) == False
, thena
is not equal tob
.
Read Java Strings to learn more.
Example:
Output: