Free for students · Ad-free · WCAG 2.1 AA Compliant · Accessibility

Boolean Expressions

Lesson ~9 min read 8 MCQs

In simple terms: In simple terms, Boolean expressions are like yes-or-no questions that help a computer make decisions, using symbols like > or == to compare values.

Why this matters

Imagine you're at an amusement park, standing in line for the biggest, fastest roller coaster, "The Goliath." There's a sign at the front with a horizontal line and a simple rule: "You must be this tall to ride." An employee, let's call her Maya, stands there with a measuring stick. When you get to the front, she doesn't need a long conversation. She performs a single check: is your height greater than or equal to the line on the sign? The answer is either a simple "yes" or a simple "no."

That quick, decisive check is exactly what we're learning about today. In programming, we need a way to ask these yes-or-no questions to make our programs react to different situations. We'll learn how to write these questions, called Boolean expressions, using a special set of tools called relational operators.

Concept overview

flowchart TD
    A[Start] --> B{int customerAge = 72};
    B --> C{customerAge >= 65?};
    C -- Yes --> D[Expression is true];
    C -- No --> E[Expression is false];
    D --> F[End];
    E --> F[End];
This flowchart shows how a Boolean expression is evaluated for a senior discount. It starts, a variable for age is set to 72, then a diamond-shaped decision node asks 'Is customerAge greater than or equal to 65?'. The 'Yes' path leads to a box that says 'Expression is true', while the 'No' path leads to a box that says 'Expression is false'. Both paths lead to the end.

Core explanation

Hello there! I'm Saavi, and I'm so glad you're here. Today, we're diving into one of the most important concepts in all of programming: making decisions.

At its heart, a computer program is often just following a list of instructions. But the real power comes when a program can make a choice. To do that, it first needs to ask a question.

The Question and the Answer: Boolean Expressions

In Java, a question that can be answered with a simple true or false is called a Boolean expression.

Think about these questions:

  • Is the temperature outside less than 32°F? (true or false)
  • Is your grade in this class greater than or equal to 90? (true or false)
  • Is your name "Marcus"? (true or false)

Every single one of these evaluates to a simple, two-option answer. This true or false value is a fundamental data type in Java, called a boolean.

An expression that results in a boolean value is a Boolean expression. This directly covers one of our key learning goals: any expression using the operators we're about to discuss will evaluate to a boolean.

The Tools for Asking: Relational Operators

To build these questions in Java, we use relational operators. They let us compare two values.

Let's look at the operators for numbers (int, double, etc.):

Operator What it means Example (age = 17) Result
> Greater than age > 16 true
< Less than age < 16 false
>= Greater than or equal to age >= 17 true
<= Less than or equal to age <= 17 true

[[fig:greater_than_or_equal_mistake]]

int myScore = 88;
int passingScore = 70;

boolean isHigher = myScore > passingScore; // 88 > 70 is true
boolean isPerfect = myScore >= 100;      // 88 >= 100 is false

System.out.println(isHigher);  // Prints: true
System.out.println(isPerfect); // Prints: false

Checking for Sameness: == and !=

What if we want to know if two values are exactly the same or not? We have two more operators for that.

Operator What it means Example (itemsInCart = 5) Result
== Equal to itemsInCart == 5 true
!= Not equal to itemsInCart != 10 true
  • int x = 5; means "put the value 5 into the variable x."
  • x == 5; means "is the value in x the same as 5?" (This would evaluate to true).

If you use a single = when you mean to compare, you'll get an error. It's a rite of passage for every new programmer to make this mistake. Just be aware of it!

The Big Trap: Primitives vs. Objects

Now for the most important, and trickiest, part of this lesson. The == operator behaves differently depending on what you are comparing.

Think of it like this: imagine you have two friends, Liam and Sofia, and you give them each a $5 bill.

  • A primitive type (int, double, boolean) is like the value on the bill. If you ask, "Does Liam's bill have the same value as Sofia's bill?", the answer is yes. They're both worth $5.
  • When you use == with primitives, you are comparing their values.
int liamsValue = 5;
int sofiasValue = 5;
boolean areValuesEqual = (liamsValue == sofiasValue); // This is true. 5 is equal to 5.

Now, imagine you have one car—a specific, single Toyota Camry parked in a specific spot in a Chicago parking garage.

  • An object (like a String or any other non-primitive type) is like that specific car.
  • A reference variable is like a slip of paper with the car's location written on it ("Section A, Spot 32").

If you give Liam and Sofia each a slip of paper with "Section A, Spot 32" written on it, they are both pointing to the exact same car.

If you buy a second, identical Toyota Camry and park it in "Section B, Spot 18," and give Sofia a new slip of paper with that location, they now have two different cars that just happen to look the same.

When you use == with objects, you are asking: "Do these two slips of paper point to the exact same spot in the parking garage?" You are not asking if the cars are identical.

// Scenario 1: Two references, ONE object.
String carLocation = new String("Section A, Spot 32");
String liamsSlip = carLocation;
String sofiasSlip = carLocation;

// Are they pointing to the SAME object in memory?
boolean sameObject = (liamsSlip == sofiasSlip); // This is true.

// Scenario 2: Two references, TWO different but identical objects.
String car1 = new String("Toyota Camry");
String car2 = new String("Toyota Camry");

// Are they pointing to the SAME object in memory?
boolean sameCarObject = (car1 == car2); // This is FALSE!

This is a huge source of bugs. car1 and car2 are two separate objects in your computer's memory that happen to contain the same text. The == operator sees two different memory addresses and returns false. We'll learn the correct way to compare the contents of objects (using a method called .equals()) in a later unit, but for now, you must understand that == on objects checks for an identical location in memory, not identical content.

See it in action

python
Line 1
Output
Click Run to see the output.

        
Try these
    © Shrutam.ai

    Worked examples

    Let's walk through a few examples to make this crystal clear. The key is to read the expression, substitute the values, and then evaluate to true or false.

    Example 1

    Amusement Park Height Check

    Problem: The "Cosmic Leap" ride at an Atlanta amusement park has a minimum height requirement of 52 inches. Aaliyah is 54 inches tall, and her younger brother Jordan is 51 inches tall. Write Boolean expressions to check if each of them can ride.

    Solution Walkthrough:

    1. 1
      Identify the core question
      Is the person's height greater than or equal to 52 inches?
    2. 2
      Choose the right operator
      The phrase "greater than or equal to" translates directly to the >= operator.
    3. 3
      Set up the variables
      int heightRequirement = 52;
      int aaliyahsHeight = 54;
      int jordansHeight = 51;
    4. 4
      Write the expression for Aaliyah
      boolean canAaliyahRide = (aaliyahsHeight >= heightRequirement);
      • Java substitutes the values: (54 >= 52).
      • It evaluates the expression: 54 is indeed greater than 52, so the result is true.
    5. 5
      Write the expression for Jordan
      boolean canJordanRide = (jordansHeight >= heightRequirement);
      • Java substitutes the values: (51 >= 52).
      • It evaluates the expression: 51 is not greater than or equal to 52, so the result is false.

    Why this matters: A common mistake here is to just use >. But what if a person is exactly 52 inches tall? They should be allowed to ride! Using >= correctly includes that boundary case. Always think about the "equal to" part.

    Example 2

    Checking for an Exact Match

    Problem: A school's online portal flags a student's account if they have exactly 0 missing assignments. Priya has 0 missing assignments. Carlos has 3. Write a Boolean expression that would evaluate to true for Priya and false for Carlos.

    Solution Walkthrough:

    1. 1
      Identify the core question
      Is the number of missing assignments exactly equal to 0?
    2. 2
      Choose the right operator
      The phrase "exactly equal to" translates to the == operator. Remember, not =!

    [[fig:equality_vs_assignment]]

    1. 1
      Set up the variables
      int priyasMissing = 0;
      int carlosMissing = 3;
    2. 2
      Write the expression for Priya
      boolean priyaIsFlagged = (priyasMissing == 0);
      • Substitute: (0 == 0).
      • Evaluate: This is true.
    3. 3
      Write the expression for Carlos
      boolean carlosIsFlagged = (carlosMissing == 0);
      • Substitute: (3 == 0).
      • Evaluate: This is false.

    Where students go wrong: The biggest mistake here is typing priyasMissing = 0. This is an assignment, not a comparison. It tries to assign the value 0 to the variable, which is not what we want. We want to ask a question, and for that, we need the double equals sign, ==.

    Try it yourself

    Time to try it on your own. Don't worry about writing a full program, just focus on writing the single line that represents the Boolean expression.

    1. 1
      Social Media Verification
      You're coding a feature for a new app based in Seattle. To get a "power user" badge, a user must have more than 500 posts. Create a boolean variable isPowerUser and assign it the result of an expression that checks if a user with numPosts qualifies.
    2. 2
      Sales Tax Exemption
      In some states, certain items are exempt from sales tax. Let's say an item is tax-exempt if its category code is exactly 107. Write a Boolean expression that evaluates to true if itemCode is tax-exempt.