if Statements
Why this matters
Imagine you're getting ready to leave for school. You glance out the window. Is it raining? This simple question creates a fork in your morning routine. If the answer is yes, you grab your umbrella. If the answer is no, you leave it behind. You just ran a program in your head.
Your brain automatically evaluated a condition (is it raining?) and chose an action based on the outcome. Our code needs to do this all the time. What if a user tries to log in with the wrong password? What if a player in a game runs out of health? What if a customer's shopping cart total qualifies for free shipping?
In this lesson, we'll learn how to give our programs this decision-making power using if statements. We'll start with simple one-way choices and then build up to the two-way "if this, then that, otherwise do this other thing" logic you use every day.
Concept overview
flowchart TD
A[Start] --> B{Is cart total > $75?};
B -- Yes --> C[Set shipping to $0];
B -- No --> D[Keep standard shipping cost];
C --> E[End];
D --> E[End];
Core explanation
Think of a simple program as a recipe. You follow the steps in order, from first to last, without skipping.
- Preheat oven to 350°F.
- Mix flour and sugar.
- Bake for 30 minutes.
This is called sequential execution. It’s the default behavior of your code. But what if you need to make a choice? What if the recipe said, "If you're making a chocolate cake, add cocoa powder"? That's a decision point. In Java, we create these decision points with if statements.
The One-Way if Statement
A one-way if statement is for when you only need to do something extra under a specific condition. If the condition isn't met, you just move on.
Think about an online store. They might offer free shipping for orders over $75.
The logic is: If the cart total is greater than $75, then set the shipping cost to $0. If it's not, you do... nothing. The shipping cost just stays what it was.
Here’s how that looks in Java:
double cartTotal = 82.50;
double shippingCost = 5.99;
// Check if the condition is true
if (cartTotal > 75.00) {
// This code ONLY runs if the condition is true
System.out.println("Congrats! You qualify for free shipping.");
shippingCost = 0.00;
}
// This line runs regardless, after the if statement is done
System.out.println("Your shipping cost is: $" + shippingCost);
Let's break it down:
if: This is the keyword that starts the selection statement.(cartTotal > 75.00): This is the Boolean expression, our condition. It must evaluate to eithertrueorfalse. Here, since82.50is greater than75.00, it evaluates totrue.{ ... }: These curly braces define the body of theifstatement. Any code inside this block will only execute when the condition istrue.- Because the condition was
true, the code inside the braces runs. It prints the "Congrats!" message and setsshippingCostto0.00. The final output will be "Your shipping cost is: $0.0".
What if cartTotal was $50.00? The condition 50.00 > 75.00 would be false. The entire block of code inside the curly braces would be skipped. The program would jump right to the final System.out.println, and the output would be "Your shipping cost is: $5.99".
The Two-Way if-else Statement
Sometimes, doing nothing isn't enough. You need to provide an alternative action. This is a two-way choice: if the condition is true, do one thing; otherwise (else), do a different thing.
Let's check if a student, Priya, is old enough to vote. The voting age in the US is 18.
The logic is: If Priya's age is 18 or greater, then print "You are eligible to vote." Else (otherwise), print "You are not yet eligible to vote."
This creates two distinct paths. Priya is either eligible or she isn't. One of these two things must be true.
Here’s the Java code:
int priyasAge = 17;
if (priyasAge >= 18) {
// This is the "true" path
System.out.println("You are eligible to vote.");
} else {
// This is the "false" path
System.out.println("You are not yet eligible to vote.");
}
// The program continues here after one of the above blocks has run.
Let's trace this:
- The condition is
priyasAge >= 18. - Since
priyasAgeis17, the expression17 >= 18evaluates tofalse. - Because the condition is
false, the program skips theifblock. - It moves to the
elsekeyword and executes the code in theelseblock. - The output will be "You are not yet eligible to vote."
If priyasAge were 25, the condition 25 >= 18 would be true. The if block would execute, printing "You are eligible to vote." The else block would be completely ignored.
This is a critical point: With an if-else statement, exactly one block of code—either the if body or the else body—will always run. Never both, and never neither.
This ability to change the path of execution is fundamental. if and if-else statements are what allow our programs to react differently to different inputs and situations, moving them from simple calculators to dynamic, intelligent applications.
See it in action
Worked examples
Let's walk through a couple of examples to solidify this. The key is to think like the computer, evaluating the Boolean condition first.
Applying a Movie Ticket Discount
Problem: A movie theater in Boston offers a discount for matinee showings before 5 PM. The standard ticket price is $15. If the movie time is before 5 PM (represented as 17:00 in 24-hour time), the price is reduced to $11. Write a program that calculates the final ticket price for a movie at 2 PM (14:00).
Step-by-Step Solution:
- 1Identify the variablesWe need a variable for the standard price and another for the movie time.
double ticketPrice = 15.00; int movieTime = 14; // Using 24-hour format, so 2 PM is 14 - 2Determine the conditionThe discount applies if the time is before 5 PM (17:00). So, our Boolean expression is
movieTime < 17. - 3
Structure the
ifstatement. This is a one-wayif. If the condition is met, we change the price. If not, the price just stays at its default value.if (movieTime < 17) { // This is the "matinee discount" block ticketPrice = 11.00; System.out.println("Applying matinee discount..."); } - 4Trace the code
- The program checks
if (14 < 17). - This condition is
true. - Therefore, the code inside the
ifblock executes.ticketPriceis updated from15.00to11.00, and the message is printed.
- The program checks
- 5Show the final result
System.out.println("Final ticket price: $" + ticketPrice); // Output will be: // Applying matinee discount... // Final ticket price: $11.0
Where students go wrong: A common mistake is to try to do the calculation in the condition, like if (ticketPrice = 11.00). Remember, the condition is the question you're asking (is the time before 5 PM?), and the block is the action you take (change the price).
Checking a Password
Problem: Write a program that checks if a user-entered password is correct. The correct password is "GoHuskies!24". If it's correct, print "Access Granted". If it's incorrect, print "Access Denied".
Step-by-Step Solution:
- 1Set up the variablesWe need one for the correct password and one for what the user typed. We'll use
Stringvariables.String correctPassword = "GoHuskies!24"; String userInput = "gohuskies!24"; // Note the lowercase 'g' - 2Determine the conditionWe need to check if the
userInputis exactly equal to thecorrectPassword. This is where most students slip up with Strings! You cannot use==to compare the content of Strings. You must use the.equals()method.- Wrong
if (userInput == correctPassword) - Correct
if (userInput.equals(correctPassword))
- Wrong
- 3
Structure the
if-elsestatement. We have two distinct outcomes: access granted or access denied. This is a perfect fit for a two-wayif-else.if (userInput.equals(correctPassword)) { // True path: Passwords match System.out.println("Access Granted"); } else { // False path: Passwords do not match System.out.println("Access Denied"); } - 4Trace the code
- The program calls the
.equals()method:userInput.equals(correctPassword). - It compares
"gohuskies!24"to"GoHuskies!24". Because of the different capitalization, these Strings are not equal. The method returnsfalse. - Since the condition is
false, theifblock is skipped, and theelseblock is executed. - The output will be:
Access Denied.
- The program calls the
This example highlights not just the if-else structure but also a crucial detail about comparing Strings, which is a very common scenario for conditional logic.
Try it yourself
Time to try it on your own. Don't worry about getting it perfect on the first try; focus on setting up the logic.
- 1Even or Odd?Write a program that takes an integer variable, let's call it
number, and determines if it is even or odd. Print "The number is even." or "The number is odd." accordingly. - 2Amusement Park RideAn amusement park ride in Chicago has a height requirement: you must be at least 48 inches tall to ride. Write a program that checks a
heightInInchesvariable. If the person is tall enough, print "You can ride the roller coaster!" Otherwise, print "Sorry, you are not tall enough to ride."
Practice — 8 questions
In simple terms, if statements let your program make decisions. If a condition is true, the code does one thing; otherwise, it can do something else or nothing at all.
double cartTotal = 82.50;
double shippingCost = 5.99;
// Check if the condition is true
if (cartTotal > 75.00) {
// This code ONLY runs if the condition is true
System.out.println("Congrats! You qualify for free shipping.");
shippingCost = 0.00;
}
// This line runs regardless, after the if statement is done
System.out.println("Your shipping cost is: $" + shippingCost);
- 2.3.A: Develop code to represent branching logical processes by using selection statements and determine the result of these processes.
- 2.3.A.1
- Selection statements change the sequential execution of statements.
- 2.3.A.2
- An if statement is a type of selection statement that affects the flow of control by executing different segments of code based on the value of a Boolean expression.
- 2.3.A.3
- A one-way selection (if statement) is used when there is a segment of code to execute under a certain condition. In this case, the body is executed only when the Boolean expression is true.
- 2.3.A.4
- A two-way selection (if-else statement) is used when there are two segments of code—one to be executed when the Boolean expression is true and another segment for when the Boolean expression is false. In this case, the body of the if is executed when the Boolean expression is true, and the body of the else is executed when the Boolean expression is false.
flowchart TD
A[Start] --> B{Is cart total > $75?};
B -- Yes --> C[Set shipping to $0];
B -- No --> D[Keep standard shipping cost];
C --> E[End];
D --> E[End];
Read what Saavi narrates
Hello and welcome to Shrutam. I'm Saavi, and I'm happy you're here.
Think about your morning routine. You look outside, and you ask a question: is it raining? If the answer is yes, you grab an umbrella. If the answer is no, you don't. You just made a decision that changed your actions. Our computer programs need to do the same thing all the time, and today, we're going to learn how.
Normally, code runs in a straight line, from top to bottom. But with `if` statements, we can create a fork in the road. We can tell the program to check if a certain condition is true, and then run a specific piece of code only if it is.
Let's take a simple example. Imagine we're checking if a student passed a class. A passing grade is 60 or higher. We can write an `if-else` statement to handle this.
Imagine a variable called `grade` is set to 75.
Our code will ask, "is the grade greater than or equal to 60?" Since 75 is greater than 60, that's true. So, the program will execute the 'if' block of code, and print "You passed!"
Now, what if the `grade` variable was 52? The program asks the same question: "is 52 greater than or equal to 60?" This time, the answer is false. So, the program skips the 'if' block and instead runs the 'else' block, which might print "You need to retake the test."
This is the power of an `if-else` statement. It gives you two paths, a 'true' path and a 'false' path, and the program will always take exactly one of them.
Now, here's a very common mistake I see all the time. When you're checking if two numbers are equal, you have to use two equal signs, like 'x, double equals, 5'. If you only use one equal sign, you're not asking a question, you're giving a command. You're trying to assign a value, and that will cause an error in your `if` statement. It's a small detail, but it's incredibly important.
You're building a foundational skill here. The ability to control which parts of your code run, and when, is what will make your programs smart and responsive. You can do this. Let's keep going.
`int x = 5; if (x = 10)` tries to *assign* the value 10 to `x` inside the `if` statement. This is not a boolean `true`/`false` question, and your code will not compile.
Use `==` for comparison with primitive types (like `int`, `double`, `boolean`). `if (x == 10)` asks the question, "is `x` equal to 10?".
`if (score > 90); { ... }` The semicolon terminates the `if` statement. The computer sees it as: "If the score is over 90, do nothing." Then, the block `{...}` that follows is treated as a separate, regular piece of code that *always* runs, no matter what the score was. This is a sneaky bug.
Never put a semicolon between the `if (condition)` and its opening curly brace `{`.
If you omit the braces, the `if` or `else` only applies to the very next line of code.
Always use curly braces, even for single-line blocks. It makes your code clearer and prevents these hard-to-find errors.
// CORRECT
if (isMember == true) {
System.out.println("Welcome back!");
discount = 0.10;
}
`==` checks if two `String` variables point to the exact same object in memory. It does not check if their character sequences are identical. This can lead to unexpected `false` results.
Always use the `.equals()` method to compare the content of two strings: `if (password.equals("secret123"))`.
`if (x > 5) { ... } else if (x <= 5) { ... }` The second check is unnecessary. If the first condition (`x > 5`) is false, the only other possibility is that `x` is less than or equal to 5. The `else` handles this automatically.
Let the `else` do its job. It's the catch-all for when the `if` condition is false. `if (x > 5) { ... } else { ... }`.