Control Flow in Java
Learn conditionals, switch expressions, and loops in Java with practical Docker-ready examples covering if/else, for, while, and loop control
Control flow is how a program decides what to do next. Instead of running every line top to bottom, control flow lets your code branch based on conditions and repeat work with loops. Mastering it is the difference between a program that follows a fixed script and one that reacts to data.
As a statically typed, class-based object-oriented language, Java inherits its control flow syntax from the C family — curly braces delimit blocks, parentheses wrap conditions, and conditions must evaluate to a boolean (not an integer, as in C). This strict typing means the compiler rejects accidental mistakes like if (x = 5) that silently bite you in other languages.
In this tutorial you’ll learn Java’s conditional statements (if/else if/else), the ternary operator, modern switch expressions introduced in recent Java versions, and the four loop forms (for, enhanced for, while, and do-while) along with the break and continue keywords that fine-tune iteration.
Conditionals: if, else if, and the Ternary Operator
The if statement runs a block only when its boolean condition is true. Chain conditions with else if, and provide a fallback with else. For simple value selection, the ternary operator condition ? a : b is a compact one-line alternative.
Create a file named Conditionals.java:
| |
Note that Java requires the condition inside if (...) to be a genuine boolean. Writing if (score) with an int is a compile error — a deliberate guardrail that catches a whole class of bugs.
Switch Expressions
When you need to branch on a single value across many cases, a switch is cleaner than a long if/else if chain. Modern Java (14+) provides switch expressions using arrow (->) syntax. Unlike the old switch statement, arrows don’t “fall through” to the next case, so no break is needed, and the whole switch can return a value.
Create a file named SwitchExample.java:
| |
The default branch is required when the switch is used as an expression that must always produce a value, ensuring every possible input is handled.
Loops: for, for-each, while, and do-while
Loops repeat a block of code. Java offers four forms:
for— best when you know the iteration count or need an index counter.- Enhanced
for(for-each) — iterates over every element of an array or collection. while— repeats as long as a condition holds, checking before each pass.do-while— likewhile, but checks after each pass, so the body always runs at least once.
Create a file named Loops.java:
| |
Loop Control: break and continue
Inside any loop, break exits the loop immediately, while continue skips the rest of the current iteration and moves to the next one. They let you short-circuit work without restructuring the loop condition.
Create a file named LoopControl.java:
| |
Running with Docker
Each example is a standalone class. Compile and run it inside the official Eclipse Temurin JDK image — no local Java installation required.
| |
Expected Output
Running Conditionals:
Grade: B
It is cool today
No work today!
Running SwitchExample:
Day 3 is Wednesday
Day 3 is a work day
Running Loops:
Squares: 1 4 9 16 25
JVM language: Java
JVM language: Kotlin
JVM language: Scala
T-minus 3
T-minus 2
T-minus 1
Liftoff!
Attempt 1
Attempt 2
Running LoopControl:
Odd numbers under 10: 1 3 5 7 9
Key Concepts
- Conditions must be boolean — Java rejects
if (x = 5)orif (someInt)at compile time, eliminating a common C-family bug. - Ternary for compact choices —
condition ? a : bis an expression that returns a value, ideal for simple assignments. - Switch expressions are modern and safe — arrow (
->) syntax has no fall-through, needs nobreak, and can return a value directly. - Four loop forms, each with a purpose — use
forfor counters, enhancedforfor collections,whilefor condition-driven repetition, anddo-whilewhen the body must run at least once. do-whilealways runs once — its condition is checked after the body, unlikewhilewhich checks before.breakandcontinuerefine loops —breakexits a loop entirely;continueskips to the next iteration.- Curly braces are best practice — while Java allows single-statement bodies without braces, always using
{ }prevents subtle errors when code is later edited.
Running Today
All examples can be run using Docker:
docker pull eclipse-temurin:21-jdk
Comments
Loading comments...
Leave a Comment