MOBI BOOT CAMP CORP. logoLearning Buddy
  • SIGN IN
  • Introduction
  • Unit 0: The First Program
  • Unit 1: Using Objects and Methods
  • Unit 2: Selection and Iteration
    • Part 1: Selection
      • Algorithms with Selection and Repetition
      • Boolean Expressions
      • if Statements
      • Nested if Statements
      • Compound Boolean Expressions
      • Comparing Boolean Expressions
      • Unit 2 Part 1 Slides
    • Part 2: Iteration
  • Unit 3: Class Creation
  • Unit 4: Data Collections

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 boolean value, 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);
    }
}
Privacy Policy | Terms & Conditions