Relational operators
- Relational operators are used to compare two values.
- There are six relational operators in Java.
- Relational operators help to determine equality and ordering.
- In Java, any data type can be compared using relational operators.
Operator | Function | Explanation |
---|---|---|
== | Equal to | Compares whether given two values are equal or not. If equal output is true, or if not equal output is false. Any data type in Java can be compared using this operator. |
!= | Not equal to | Compares whether given two values are not equal or not. If not equal output is true, or if equal output is false. Any data type in Java can be compared using this operator. |
> | Greater than | Compares whether the left side value is greater than the right side value. If greater, output is true, or if less, output is false. |
< | Less than | Compares whether the left side value is less than the right side value. If less, output is true, or if greater, output is false. |
>= | Greater than or equal to | Compares whether the left side value is greater than or equal to the right side value. If greater than or equal, output is true, or if less, output is false. |
<= | Less than or equal to | Compares whether the left side value is less than or equal to the right side value. If less than or equal, output is true, or if greater, output is false. |
- Relational operators are mainly used in ‘if’ conditions and loops. (Don’t worry we will learn about ‘if’ and ‘loops’ on later lessons.)
// Equal to
i == j
// Not equal to
i != j
// Greater than
i > j
// Less than
i < j
// Greater than or equal to
i >= j
// Less than or equal to
i <= j
- The outputs of relational operators are boolean values. (True or False)
- If we print the value of a relational operator, we will get either 'true' or 'false' depending on the scenario.
int a = 10;
int b = 12;
System.out.println(a == b);
System.out.println(a != b);
false true
Which relational operator will give out a "true" output if the left side value is not-equal to the right side value in a given expression.