Understanding Comparison Operators in Programming

Sep 24, 2024

Introduction to Comparison Operators

What Are Comparison Operators?

  • Tools to compare two values.
  • Example:
    • int x = 15;
    • int y = 10;
    • boolean z = x > y; (results in true because 15 is greater than 10)

Types of Comparison Operators

  • Equal to: ==
  • Not equal to: !=
  • Less than: <
  • Greater than: >
  • Less than or equal to: <=
  • Greater than or equal to: >=

Usage

  • Used to compare primitive types: int, double, boolean, char
  • Not typically used for strings (more complex)

Example Scenarios

Roller Coaster Height Check

  • Input: int heightInInches = readInt("What is your height?");
  • Logic: boolean canRide = heightInInches >= 50;
    • Determines if the user can ride based on being at least 50 inches tall.

Grade Evaluation

  • Input: int grade = readInt("What was your grade?");
  • Boolean: boolean gotB = (grade >= 80) && (grade < 90);
    • Checks if a grade is between 80 and 90.

Code Demonstration

  • Input Grade:
    int grade = readInt("What was your grade?");
    boolean gotB = (grade >= 80) && (grade < 90);
    System.out.println("Got a B: " + gotB);
    
  • Test Cases:
    • Grade 85: true (B-grade)
    • Grade 80: true (B-grade, edge case)
    • Grade 90: false (not a B)
    • Grade 74: false (not a B)

Key Takeaways

  • Comparison operators allow for the evaluation of relationships between values.
  • Logical operators like AND (&&) are used to combine comparison conditions.
  • Practical application includes determining eligibility or classifications based on input values.