2.2 Boolean Expressions
1. Exam Points
Relational operators: <, >, <=, and >=, ==, !=
- An expression with relational operators evaluates to a
Boolean value.
- 10 > 3 // true
- 10 < 3 == 2 > 5 // true
Operator Precedence
- Parentheses ()
- Arithmetic operators (+, - , *, / , %)
- Relational operators (<, >, <=, and >=, ==, !=)
- Assignment = (lowest precedence)
- Example
- 2+3 > 4+5
- boolean flag = (2+3 == 6) == (7+8 > 12)
Compare primitive types using ==
- two primitive variables or values are equal if their values are equal
- two reference variables are equal if they refer to the same object
- you may override the
equals() method to use an attribute to indicate equality
Note: result type of an expression
- 3 + 2 (result : 5)
- 3 + 2 == 6 (result : false)
- 5 == 8 (result : false)
- (5 < 8) == (5 == 8) (result : false)
2. Knowledge Points
(1) Relational Operators
- Values can be compared using the relational operators
== and != to determine whether the values are the same.
- With
primitive types(int, double, boolean), == or != compares the actual primitive values.
- In this example, result is
true since the value of a and b are equal.
- With
reference types(String, Student, Dog), == or != compares the object references(whether two objects are the same object).
- In this example, result is
false since the two objects are two differnt objects.
Two reference variables are equal if they refer to the same object.
Relational Operators
- An expression involving relational operators evaluates to a boolean value.
- Example: 3 > 2 evaluates to true
(2) Operator Precedence
- From the
highest to the lowest:
- Parentheses ()
- Arithmetic operators (+, - , *, / , %)
- Relational operators (<, >, <=, and >=, ==, !=)
- Assignment = (lowest precedence)
result type of an expression
- 3 + 2 (result : 5)
- 3 + 2 == 6 (result : false)
- 5 == 8 (result : false)
- (5 < 8) == (5 == 8) (result : false)
3. Exercises