1
0

Relational Operators in Java

The relational operators determine if one operand is greater than, less than, equal to, or, not equal to another operand. The majority of these operators will probably look familiar to you as well. Keep in mind that you must use “==”, not “=”, when testing two primitive values are equal. The result of a relational expression is true or false. Various relational operators are:

==  equal to
!=  not equal to
>  greater than
<  less than
>=  greater than or equal to
<=  less than or equal to

Program to test the comparison operators:

class ComparisonDemo
{
    public static void main(String[] s)
    {
        int value1 = 1;
        int value2 = 2;
        if(value1 == value2) System.out.println("value1 == value2"); // false
        if(value1 != value2) System.out.println("value1 != value2"); // true
        if(value1 > value2) System.out.println("value1 > value2"); // false
        if(value1 < value2) System.out.println("value1 < value2"); // true
        if(value1 <= value2) System.out.println("value1 <= value2"); // true
    }
}

Output:

value1 != value2
value1 < value2
value1 <= value2

Above all these operators from relations expressions, represents either true or false value. The result of these expressions will be of type Boolean i.e. true or false. The precedence of <, <=, >, >= is more than == and != operator, also the precedence of relational operators is lower than arithmetic, unary operators and associativity is from left to right.

Let a=1, b=2 and c=3. Now let us check the result using the above operators:

Expression Interpretation Value
a < b true true
(a + b) >= c true true
(a + b) > (a + 4) false false
c != 3 false false
c == 3 true true

Leave a Reply