We frequently make decisions based on specific parameters in our day-to-day lives, and similarly, we make programming decisions by comparing variables or values. This is done using a set of operators called Relational Operators. Let's take a look at Relational Operators.
Relational Operators are used to compare values. It returns true or false as the result of a comparison. Below are the different relational operators
Operator |
Name |
> |
Is greater than |
< |
Is less than |
== |
Is equal to |
<= |
Is less than or equal to |
>= |
Is greater than or equal to |
!= |
Is not equal to |
The Relational Operators in Java work similar to that in Python.
class Main { public static void main(String[] args) { System.out.println(5 < 10); System.out.println(2 < 1); } } |
class Main { public static void main(String[] args) { System.out.println(2 <= 3); System.out.println(2.53f >= 2.55f); } } |
true
false
class Main { public static void main(String[] args) { System.out.println(12 == 12.0f); System.out.println(12 == 12.1f); } } |
true
false
class Main { public static void main(String[] args) { System.out.println("ABC" == "ABC"); System.out.println("CBA" != "ABC"); } } |
true
true
Java is case-sensitive, meaning that X (capital letter) and x (small letter) are not the same.
class Main { public static void main(String[] args) { System.out.println("ABC" == "abc"); } } |
false
Comparisons using relational operators can also be made between different data types.
Example 1:
class Main { public static void main(String[] args) {
System.out.println(5 > 4.567f); System.out.println(6.89f < 7L); } } |
true
true
Likewise, we can compare any combination of int, float, and long.
Example 2:
class Main { public static void main(String[] args) { System.out.println('A' == 65); System.out.println('A' <= 64); } } |
true
false
The char can also be compared in combination with int, float, or long. The comparison takes place based on the Unicode values. In the above example, number 65 of Unicode represents character A. Hence, the output for 'A' == 65 is true and 'A' <= 64 is false
Relational operators return true or false as the result of a comparison.
Any combination of int, float and long can be compared among themselves.
Java is case-sensitive. The char can be compared with any combination of int, float, or long. The comparison takes place based on the Unicode values