Sub topic 6
Making Decisions: Control Flow Statements
This chapter assumes you have read the earlier chapters on variables and types and on operators. You should already know how to declare a variable such as int score = 75; and how to build a comparison like score >= 60 that produces a boolean value (a value that is either true or false). If those ideas feel shaky, revisit the previous chapters first.
So far, every program we have written runs its statements from top to bottom, one after another. That is called sequential execution. Real programs rarely work that way. A game must react differently depending on whether you press left or right. A login screen must accept or reject your password. To do this, a program needs to make decisions, and the part of the language that does that is called control flow.
Control flow means controlling which statements run and in what order. In this chapter we focus on the decision-making statements: if, if/else, else if chains, nested decisions, and switch.
The if Statement
An if statement runs a block of code only when a condition is true. A condition is any expression that evaluates to true or false, usually built with comparison operators like <, >, ==, or >=.
int temperature = 35;
if (temperature > 30) {
System.out.println("It is hot outside.");
}Here is what happens, step by step:
- Java evaluates the expression
temperature > 30. - The value of
temperatureis 35, and 35 > 30, so the result istrue. - Because the condition is
true, Java runs the block inside the curly braces{ }. - If the condition had been
false, the block would have been skipped entirely, and the program would continue with whatever comes after it.
The braces are important. They mark exactly which statements belong to the if. A common beginner mistake is to forget them:
// Risky style: only the first statement is controlled by the if
if (temperature > 30)
System.out.println("It is hot outside.");
System.out.println("Drink water!"); // This ALWAYS runsWithout braces, only one statement is controlled. The second println runs no matter what, which is almost never what you want.
The if/else Statement
if alone lets you do something when a condition is true, but it does nothing special when the condition is false. The else clause adds the "otherwise" branch.
int score = 75;
if (score >= 60) {
System.out.println("You passed.");
} else {
System.out.println("You failed.");
}Exactly one of the two blocks will run, never both, never neither. This is called a branch: the program's path through the code splits into two possible routes.
Chaining Decisions with else if
Often you need more than two outcomes. You can chain conditions using else if. Java checks each condition from top to bottom and runs the first block whose condition is true. The rest are skipped, even if their conditions would also be true.
int score = 85;
if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 80) {
System.out.println("Grade: B");
} else if (score >= 70) {
System.out.println("Grade: C");
} else {
System.out.println("Grade: F");
}With score = 85, the first condition 85 >= 90 is false, so Java moves on. The second condition 85 >= 80 is true, so it prints "Grade: B" and skips the rest.
Order matters enormously here. If you checked score >= 70 first, an 85 would print "Grade: C" and stop, never reaching the "B" branch. When chaining, put the most specific or strictest condition first.
Comparing Values: A Common Trap
To test whether two values are equal, Java uses == (two equals signs). A single = assigns a value instead of comparing, so if (x = 5) is an error when x is an int, because the condition must be boolean.
There is a second, sneakier trap. The == operator works fine for numbers, but it does not work the way you might expect for text. A String (Java's type for text) is an object, and == on objects asks "are these the same object in memory?" rather than "do these contain the same characters?"
String a = "hello";
String b = new String("hello");
System.out.println(a == b); // false!
System.out.println(a.equals(b)); // trueFor comparing text, always use the .equals() method. We cover this in depth in the Strings chapter, but it is worth flagging now because it bites almost every beginner eventually.
Nested if Statements
An if statement can sit inside another if block. This is called nesting, and it lets you combine conditions hierarchically: first check one thing, then, only if that passed, check something else.
int age = 20;
boolean hasTicket = true;
if (age >= 18) {
if (hasTicket) {
System.out.println("Enjoy the show!");
} else {
System.out.println("You need a ticket.");
}
} else {
System.out.println("Sorry, adults only.");
}The inner if only runs when the outer condition is true. Nesting is useful, but deeply nested code gets hard to read. If you find yourself three or more levels deep, consider combining conditions with the logical operators && (and) and || (or) from the operators chapter:
if (age >= 18 && hasTicket) {
System.out.println("Enjoy the show!");
} else {
System.out.println("Check age or ticket.");
}The two versions are not identical in behavior when the age check fails, so think carefully about which failure message you actually want to show. Choosing between nested conditions and combined conditions is a design decision, not just a style one.
The switch Statement
switch is an alternative to long else if chains when you are comparing one variable against several fixed values. It reads more cleanly for cases like handling a menu choice or a day of the week.
int dayNumber = 3;
switch (dayNumber) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Unknown day");
break;
}How it works:
- Java compares
dayNumberagainst eachcasevalue in turn. - When it finds a match (here,
case 3), it runs the statements from that point. - The
breakkeyword says "stop here and leave the switch." Without it, execution falls through into the next case, which is a classic source of bugs. defaultruns when no case matched. It is like the finalelsein a chain.
Modern Java (14 and later) also supports a cleaner arrow syntax that does not fall through:
String day = switch (dayNumber) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
default -> "Unknown day";
};This form assigns a result directly to a variable and cannot accidentally fall through, so it is the preferred style in new code when your Java version supports it.
Choosing the Right Tool
| Situation | Best choice | Column | Column |
|---|---|---|---|
| One condition, one action | `if` | ||
| Do this or that | `if/else` | ||
| Ranges, like grade bands | `else if` chain | ||
| One variable against many fixed values | `switch` | ||
| Combine several conditions | `&&` and `\ | \ | ` inside one `if` |
Putting It Together: A Small Decision Program
public class Admission {
public static void main(String[] args) {
int age = 19;
boolean hasTicket = true;
int memberLevel = 2;
if (age < 18) {
System.out.println("Entry refused: adults only.");
} else if (!hasTicket) {
System.out.println("Entry refused: no ticket.");
} else {
switch (memberLevel) {
case 1 -> System.out.println("Welcome! Regular seating.");
case 2 -> System.out.println("Welcome! Premium seating.");
case 3 -> System.out.println("Welcome! VIP lounge access.");
default -> System.out.println("Welcome! Standard entry.");
}
}
}
}This program uses a chain to reject impossible cases first, then a switch to pick a greeting. Save it as Admission.java, compile with javac Admission.java, and run with java Admission. Try changing age, hasTicket, and memberLevel and predict the output before running it.
Exercise
What does this print, and why? int x = 10; if (x > 5) System.out.println("A"); System.out.println("B");
Show answer
It prints both A and B. Without curly braces, the if controls only the first statement; the second println always runs.
Exercise
Rewrite this nested if using the && operator: if (age >= 18) { if (hasID) { System.out.println("Allowed"); } }
Show answer
if (age >= 18 && hasID) { System.out.println("Allowed"); }
Exercise
A switch case omits its break statement. What happens when that case matches?
Show answer
Execution falls through: after running the matching case's statements, Java continues running the next case's statements until it hits a break or the end of the switch, usually producing unwanted output.
Exercise
Which is wrong here, and why: if (name == "Alice") where name is a String read from user input?
Show answer
== compares object identity, not the characters inside the strings. For a String from user input this is almost certainly false even when the text matches. Use name.equals("Alice") instead.