Boolean Expressions
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];
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 totrue).
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
Stringor 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
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.
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:
- 1Identify the core questionIs the person's height greater than or equal to 52 inches?
- 2Choose the right operatorThe phrase "greater than or equal to" translates directly to the
>=operator. - 3Set up the variables
int heightRequirement = 52; int aaliyahsHeight = 54; int jordansHeight = 51; - 4Write 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.
- Java substitutes the values:
- 5Write 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.
- Java substitutes the values:
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.
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:
- 1Identify the core questionIs the number of missing assignments exactly equal to 0?
- 2Choose the right operatorThe phrase "exactly equal to" translates to the
==operator. Remember, not=!
[[fig:equality_vs_assignment]]
- 1Set up the variables
int priyasMissing = 0; int carlosMissing = 3; - 2Write the expression for Priya
boolean priyaIsFlagged = (priyasMissing == 0);- Substitute:
(0 == 0). - Evaluate: This is
true.
- Substitute:
- 3Write the expression for Carlos
boolean carlosIsFlagged = (carlosMissing == 0);- Substitute:
(3 == 0). - Evaluate: This is
false.
- Substitute:
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.
- 1Social Media VerificationYou'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
isPowerUserand assign it the result of an expression that checks if a user withnumPostsqualifies. - 2Sales Tax ExemptionIn 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
trueifitemCodeis tax-exempt.
Practice — 8 questions
In simple terms, Boolean expressions are like yes-or-no questions that help a computer make decisions, using symbols like > or == to compare values.
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
- 2.2.A: Develop code to create Boolean expressions with relational operators and determine the result of these expressions.
- 2.2.A.1
- Values can be compared using the relational operators == and != to determine whether the values are the same. With primitive types, this compares the actual primitive values. With reference types, this compares the object references.
- 2.2.A.2
- Numeric values can be compared using the relational operators <, >, <=, and >= to determine the relationship between the values.
- 2.2.A.3
- An expression involving relational operators evaluates to a Boolean value.
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];
Read what Saavi narrates
(Sound of a gentle, encouraging classroom)
Hi everyone, it's Saavi. I'm so glad you're here with me.
Let's talk about making choices. Imagine you're at an amusement park, standing in front of a huge roller coaster. There's a sign that says, "You must be this tall to ride." An employee stands there, and their job is to perform a single, simple check: is your height greater than or equal to the line on the sign? The answer is just yes, or no.
That's exactly what we're learning to do in our code today. We're learning how to ask the computer simple yes-or-no questions. These questions are called Boolean expressions, and they always have a simple true or false answer. This is the first step to making our programs smart and responsive.
Let's try a quick example. Imagine a movie theater in Boston that gives a discount to seniors. Anyone age 65 or older gets a cheaper ticket. Let's say we have a variable called customer age. To check if they get the discount, we'd write an expression like: customer age... is greater than or equal to... sixty-five.
If the customer is 72, the expression '72 is greater than or equal to 65' evaluates to true. They get the discount! If the customer is 40, the expression '40 is greater than or equal to 65' evaluates to false. They pay the full price. That true or false answer is what the computer uses to make a decision.
Now, one of the most common mistakes I see every single year is with the equals sign. In math, a single equals sign means 'is equal to'. But in Java, you need two of them. A double equals sign asks the question, "Are these two things the same?" A single equals sign is for assignment... it's for telling the computer, "Put this value in this box." So if you're asking a question, you need two equals signs. It's a tiny detail that makes a huge difference.
You're building the foundation for everything that comes next. This skill of asking questions is what allows us to build complex, interesting programs. Keep practicing, stay curious, and know that you can absolutely do this. You've got this.
`=` is the assignment operator. It tells the computer to place a value into a variable. `==` is the equality operator; it asks if two values are the same. `if (score = 100)` is an error; `if (score == 100)` is a question.
When you want to check if two things are equal, always use the double equals sign (`==`).
`==` on objects compares their memory addresses (references), not their contents. `new String("hi") == new String("hi")` is `false` because they are two separate objects in memory.
To compare the actual content of `String` objects, you must use the `.equals()` method, like this: `string1.equals(string2)`. We'll cover this more later, but it's the right way.
Java evaluates from left to right. It would first solve `5 < x`, which becomes `true` or `false`. Then it would try to solve `true < 10`, which makes no sense and causes an error. You can't compare a boolean to a number.
You must break it into two separate expressions joined by a logical operator (which we'll learn about next!): `x > 5 && x < 10`.
Students sometimes try to write `x == !5` or something similar. The `!` operator works on booleans, not numbers.
The "not equal to" operator is a single unit: `!=`. Always write it as `x != 5`.
This leads to "off-by-one" errors. If a discount applies to ages "65 and up," using `age > 65` would incorrectly exclude people who are exactly 65.
Read the problem carefully. If the boundary value is included ("up to and including 10", "at least 18"), you must use `<=` or `>=`.