Control Statements
Every program you write needs to make decisions, repeat actions, and skip steps based on conditions. Control statements are the tools Java gives you to do exactly that — they determine which lines of code run, how many times they run, and when to stop.
Without control flow, every program would execute top-to-bottom exactly once. Control statements turn a simple list of instructions into a real, thinking program.
What Are Control Statements?
A control statement is any statement that alters the sequential execution of code. Java organizes them into three broad categories:
| Category | What It Does | Examples |
|---|---|---|
| Decision-making | Execute a block only when a condition is true | if, if-else, switch |
| Looping (Iteration) | Repeat a block zero or more times | for, while, do-while, for-each |
| Jump/Transfer | Jump out of or skip within a loop or block | break, continue, return |
Decision-Making Statements
if and if-else
The if statement is the most fundamental control statement. Java evaluates a boolean expression — if it’s true, the block runs; if it’s false, it’s skipped.
int score = 75;
if (score >= 60) {
System.out.println("You passed!");
} else {
System.out.println("Please try again.");
}
Output:
You passed!
You can chain conditions with else if to handle multiple cases. For a deeper look, visit if-else Statement.
switch Statement
When you have a single variable to compare against several specific values, switch is often cleaner than a long chain of else if blocks.
int day = 3;
String dayName;
switch (day) {
case 1: dayName = "Monday"; break;
case 2: dayName = "Tuesday"; break;
case 3: dayName = "Wednesday"; break;
default: dayName = "Other";
}
System.out.println(dayName);
Output:
Wednesday
Modern Java (14+) introduced switch expressions that are more concise and don’t require break. See switch Statement for traditional syntax and Switch Expressions for the modern form.
Looping Statements
Loops let you repeat a block of code. Choosing the right loop depends on whether you know the number of iterations in advance.
for Loop
Use a for loop when you know exactly how many times you need to iterate.
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
The for Loop page covers nested loops, variable scoping, and performance notes.
for-each Loop
The enhanced for loop (also called for-each) is the cleanest way to iterate over arrays and collections without managing an index.
String[] colors = {"Red", "Green", "Blue"};
for (String color : colors) {
System.out.println(color);
}
Output:
Red
Green
Blue
See for-each Loop for how it interacts with the Iterable interface under the hood.
while Loop
Use while when you want to repeat as long as a condition is true, but you don’t know the count upfront. The condition is checked before each iteration.
int n = 1;
while (n <= 4) {
System.out.println("n = " + n);
n++;
}
Output:
n = 1
n = 2
n = 3
n = 4
Full details at while Loop.
do-while Loop
do-while is like while, but the condition is checked after the body runs — guaranteeing the block executes at least once.
int x = 10;
do {
System.out.println("x = " + x);
x++;
} while (x < 5); // condition is false immediately, but body already ran
Output:
x = 10
This is useful for menus and input validation where you always need at least one prompt. See do-while Loop.
Jump Statements
break
break immediately exits the nearest enclosing loop or switch block.
for (int i = 0; i < 10; i++) {
if (i == 4) break;
System.out.println(i);
}
Output:
0
1
2
3
You can also use labeled break to exit outer loops. Full guide: break Statement.
continue
continue skips the rest of the current loop iteration and jumps to the next one.
for (int i = 0; i < 6; i++) {
if (i % 2 == 0) continue; // skip even numbers
System.out.println(i);
}
Output:
1
3
5
See continue Statement for labeled continue and practical use cases.
Tip: Prefer
continueover deeply nestedifblocks inside loops — it keeps your code flatter and easier to read.
Comments — Not a Flow Statement, but Essential
While comments don’t affect program execution, they guide both you and future readers through the intent behind your control flow. Java supports single-line (//), multi-line (/* */), and Javadoc (/** */) comments. Visit Comments to learn best practices.
Under the Hood
Understanding what happens at the bytecode and JVM level helps you write more efficient loops and conditions.
Branch instructions: Every if, while, and for compiles to conditional branch bytecode instructions like ifeq, ifne, iflt, ifge, goto. These are direct jumps in the constant pool — extremely cheap operations.
Loop counters: A for loop counter is typically stored in a local variable slot. The JVM’s Just-In-Time (JIT) compiler recognizes counted loops and can apply powerful optimizations like loop unrolling (expanding iterations inline to reduce branch overhead) and auto-vectorization.
Branch prediction: Modern CPUs predict which branch a conditional will take. Loops that almost always run their body (and only occasionally exit) are friendly to branch predictors. Erratic conditionals inside tight loops can cause pipeline stalls.
for-each internals: When you use a for-each on a Collection, the compiler rewrites it as an Iterator-based loop. On arrays, it compiles to a standard index-based for loop — no iterator object is created, so there’s zero allocation overhead.
Note: The JIT compiler treats small, hot loops as prime candidates for optimization. Writing clean, straightforward loops (avoid side effects and complex conditions in the loop header) makes it easier for the JIT to optimize them. See How Loops Work (Bytecode & JIT) for a deep dive.
Choosing the Right Control Statement
A quick decision guide for common scenarios:
| Scenario | Best Choice |
|---|---|
| Check one condition | if |
| Multiple fixed values for one variable | switch |
| Known iteration count | for loop |
| Iterate all elements of a collection/array | for-each |
| Loop until a condition changes | while |
| Need at least one execution guaranteed | do-while |
| Exit a loop early | break |
| Skip to next iteration | continue |
Warning: Infinite loops (
while (true)) are intentional in some cases (e.g., server loops, game loops), but always make sure there is a reachablebreakorreturnpath, or your program will hang.
In This Section
- if-else Statement — Learn how to make decisions in Java using
if,else if, andelseblocks, including nested conditions. - switch Statement — Compare a single variable against multiple values cleanly; covers fall-through,
default, and labeled breaks. - for Loop — The classic counted loop with an initializer, condition, and update expression — plus nested loops.
- for-each Loop — The cleanest way to iterate arrays and collections without an index variable.
- while Loop — Repeat while a condition is true; the condition is tested before each iteration.
- do-while Loop — Like
while, but the body always runs at least once before the condition is checked. - break Statement — Exit a loop or switch immediately; includes labeled
breakfor nested loops. - continue Statement — Skip the rest of the current iteration and jump straight to the next; includes labeled
continue. - Comments — Write single-line, multi-line, and Javadoc comments to document your control flow and logic.
- How Loops Work (Bytecode & JIT) — A deep dive into how the JVM compiles and optimizes loops at the bytecode and JIT level.
- Practice Programs — Reinforce every control statement with hands-on coding exercises and challenges.
Related Topics
- Variables — Control statements operate on variables; understand how they’re declared and scoped before building complex logic.
- Operators — Boolean and comparison operators power every condition inside your
ifand loop headers. - Switch Expressions — The modern, expression-form
switchintroduced in Java 14 that eliminates fall-through bugs. - Pattern Matching — Java 16+ pattern matching in
instanceofandswitchtakes conditional logic to the next level. - How Loops Work (Bytecode & JIT) — Go deeper into the JVM mechanics behind every loop you write.
- Practice Programs — Put your control flow knowledge to work with real coding challenges.