Unit 2.2: Boolean Expressions
Relational Operators
Relational operators compare two values and evaluate to a boolean result (true or false).
Comparison Logic
- Relational operators allow the computer to ask questions about data. The result is always a
booleanvalue, which can be stored in a variable or used directly in a conditional statement.
| Operator | Meaning | Example |
|---|---|---|
== |
Equal to | 5 == 5 is true |
!= |
Not equal to | 5 != 3 is true |
< |
Less than | 2 < 10 is true |
> |
Greater than | 10 > 2 is true |
<= |
Less than or equal to | 5 <= 5 is true |
>= |
Greater than or equal to | 3 >= 5 is false |
Comparing Values
- Primitive Types: Relational operators compare the actual values (e.g.,
3 == 3). - Reference Types: Relational operators (
==,!=) compare the memory addresses (references), not the content of the objects. To compare content, use.equals().
Identity vs. Equality
- Identity (
==): Checks if two variables point to the exact same location in memory. - Equality (
.equals()): Checks if two different objects contain the same data.
Examples
Using Relational Operators
Task: Comparing primitives and object references.
public class BooleanExample {
public static void main(String[] args) {
int age = 16;
double height = 5.9;
// Comparing primitives
boolean canDrive = age >= 16; // true
boolean isTall = height > 6.0; // false
System.out.println("Can drive? " + canDrive);
System.out.println("Is tall? " + isTall);
// Comparing references (Addresses)
String s1 = new String("Hi");
String s2 = new String("Hi");
// This is false because they are different objects in memory
boolean sameObject = (s1 == s2);
System.out.println("Same object reference? " + sameObject);
// This is true because they have the same characters
boolean sameContent = s1.equals(s2);
System.out.println("Same content? " + sameContent);
}
}