Relational and Logical Operators in Java

After the equals relational operator == the listed next are all the relational operators.


> greater than

>= greater than or equal to

< less than

<= less than or equal to



These are all of equal precedence. The remaining two operators are of lower precedence.

== equals

!= not equals



The precedence rules mean that in the following code fragment:

int a = 5, b = 4; boolean c = true; if (a > b == c)
{
System.out.println("Condition true");
}


the condition a > b == c is equivalent to (a > b) == c. The expression a > b is evaluated first and returns a value of true or false, which is then compared with the value of the boolean variable c.

More complex condition expressions can be constructed with the use of logical operators, listed in order of precedence in Table 3.1.

Expressions using logical operators are evaluated left to right. Logical operators, apart from !, have a lower precedence than the relational operators. A complete list of precedence rules is shown in Appendix A.

The && and || operators have the same function as & and |, respectively, except in the manner in which component expressions are evaluated. For example, in the expression (a
> b) & (c < d), the components are evaluated left to right, so (a > b) is evaluated first. If (a > b) is false, the entire expression is false regardless of the result of the component (c < d). Nevertheless, the component (c < d) will still be evaluated. However, in the expression (a > b) && (c < d), the component (c < d) will not
be evaluated if (a > b) evaluates to false. This is known as short circuiting.

The following code fragment illustrates the use of logical operators:

int a = 5, b = 4, c = 2, d = 3, e = 0;
if (! (a < b) )
{
System.out.println('' ! condition true");
}
if ( (a > b) & (c < d) )
{
System.out.println(" & condition true");
}
if ( (a > b) | (c < d) )
{
System.out.println(" | condition true");
}
if ( (a > b) ^ (c < d) )
{
System.out.println(" First ^ condition true");
}
Else
{
System.out.println(" First ^ condition false");
}
if ( (a > b) ^ (d < c) )
{
System.out.println(" Second ^ condition true");
}
if ((true) | | (5/e == 0))
{
System.out.println(" Divide by 0 avoided");
}
if ((true) | (5/e == 0))
{
System.out.println(" Not printed");
}


This will output

> java TestLogicals
! condition true
& condition true
| condition true
First ^ condition false
Second ^ condition true


Divide by 0 avoided
java.lang.ArithmeticException: / by zero
void TestLogicals.main(java.lang.String[])
Exception in thread main

Note: that the first ^ condition is false since both (a > b) and (c < d) are true.

No comments:

Post a Comment