Boolean Expressions – Basic Elements, Primitive Data Types, and Operators

2.11 Boolean Expressions

As the name implies, a boolean expression has the boolean data type and can only evaluate to the value true or false. Boolean expressions, when used as conditionals in control statements, allow the program flow to be controlled during execution.

Boolean expressions can be formed using relational operators (p. 74), equality operators (p. 75), boolean logical operators (p. 78), conditional operators (p. 80), the assignment operator (p. 54), and the instanceof operator (§5.11, p. 269).

2.12 Relational Operators: <, <=, >, >=

Given that a and b represent numeric expressions, the relational (also called comparison) operators are defined as shown in Table 2.23.

Table 2.23 Relational Operators

a < ba less than b?
a <= ba less than or equal to b?
a > ba greater than b?
a >= ba greater than or equal to b?

All relational operators are binary operators and their operands are numeric expressions. Binary numeric promotion is applied to the operands of these operators. The evaluation results in a boolean value. Relational operators have lower precedence than arithmetic operators, but higher than that of the assignment operators.

Click here to view code image

double hours = 45.5;
Double time = 18.0;             // Boxing of double value.
boolean overtime = hours >= 35; // true. Binary numeric promotion: double <– int.
boolean beforeMidnight = time < 24.0;// true. Unboxing of value in time reference.
char letterA = ‘A’;
boolean order = letterA < ‘a’;  // true. Binary numeric promotion: int <– char.

Relational operators are nonassociative. Mathematical expressions like a ≤ b ≤ c must be written using relational and boolean logical/conditional operators.

Click here to view code image

int a = 1, b = 7, c = 10;
boolean illegal = a <= b <= c;       // (1) Illegal. Compile-time error!
boolean valid2 = a <= b && b <= c;   // (2) OK.

Since relational operators have left associativity, the evaluation of the expression a <= b <= c at (1) in these examples would proceed as follows: ((a <= b) <= c). Evaluation of (a <= b) would yield a boolean value that is not permitted as an operand of a relational operator; that is, (boolean value <= c) would be illegal.