Section 2.26 Worked Example: Boolean Relations
Subgoals for evaluating an assignment statement.
- Determine resultant data type of expression
- Update variable for pre operators based on side effect
- Solve arithmetic equation, operator precedence
- Is the Left Hand Side (LHS) of the assignment statement a variable? Check the data type of the value on right hand side (RHS) against data type of LHS variable.
- Update variable for post operators based on side effect
Subsection 2.26.1
Given the following code snippet, evaluate the final statement (the last line). If invalid, give the reason. If valid, what value is assigned to the variable?
int alpha = 42;
int beta = 1;
int gamma = 5;
boolean result;
result = !(beta <= gamma) && gamma <= alpha;
Subsection 2.26.2 SG1 : Determine resultant data type of expression
First, note that
alpha
, beta
, and gamma
are all integers.The logical operators in Java are:
- && - AND, if both operands are true the result is true, otherwise the result is false.
- || - OR, if both operands are false the result is false, otherwise the result is true.
- ! - NOT, the opposite logical value (For example, !true is false).
In the final statement, the
<=
operator is valid to compare primitive types, and produces boolean results, which are then used with the !
and &&
operators to produce one final boolean.(You may wish to keep a precedence and associativity reference handy, until you have memorized the order of operations for boolean operators. In this example the relational operators are evaluated before the logical operators and the
!
is evaluated before the &&
.)Subsection 2.26.3 SG2: Update variables for any pre-increment or pre-decrement operators (side effects)
NOT USED IN THIS EXAMPLE
Subsection 2.26.4 SG3: Evaluate arithmetic expression according to operator precedence
Substitute the values for the variables on the RHS and evaluate according to the order of operations.
!(beta <= gamma) && gamma <= alpha
!(1 <= 5) && 5 <= 42
!(true) && true
false && true
false
Subsection 2.26.5 SG4: Is the Left Hand Side (LHS) of the assignment statement a variable? Check the data type of the value on right hand side (RHS) against data type of LHS variable.
The LHS is a variable of type
boolean
, and the RHS is type boolean
. This is valid.Subsection 2.26.6 SG5: Update variable for post-increment or post-decrement operators (side effect)
NOT USED IN THIS EXAMPLE
Answer.
result
is true
.Practice Pages.
You have attempted of activities on this page.