Java Control Flow: Decisions, Loops, and Safe Exit Conditions
A Java program usually runs statements in sequence. Control-flow statements change that order: a conditional decides which work happens, a loop repeats work, and branching statements stop or skip portions of a loop. In this lesson, you will use if, else if, switch, for, while, do-while, break, and continue.
This is OSJava.004 in Open CERT’s complete subject rotation. It follows OSJava.003: Expressions, Statements, and Blocks. Review OSJava.002: Primitive Types and OSJava.001: Your First Program if variables, boolean values, braces, or javac are unfamiliar.
Learning objectives
- Write an
if / else if / elsedecision using boolean expressions. - Compare classic colon-style and modern arrow-style
switchcases. - Identify when
for,while,do-while, or enhancedforis appropriate. - Use
continueto skip an iteration andbreakto exit a loop. - Compile a complete Java program that evaluates simulated equipment temperatures.
- Distinguish Java loop behavior from other languages without copying their syntax.
1. Choose a branch with if and else
Java requires a boolean condition inside parentheses. The first true branch runs; following branches are skipped. The threshold values below are illustrative classroom values, not a safe operating specification for any real machine.
int temperature = 76; if (temperature >= 90) { System.out.println(“ALERT: critical heat”); } else if (temperature >= 70) { System.out.println(“INSPECT COOLING”); } else { System.out.println(“NORMAL”); }
For temperature = 76, the expression temperature >= 90 is false and temperature >= 70 is true. The console prints INSPECT COOLING. Java uses && for logical AND, || for OR, and ! for negation. Unlike Go, parentheses around an if condition are mandatory.
2. Choose one case with switch
A classic switch matches a selector against case labels. In the colon form, break commonly prevents execution from falling into the next case. The arrow form, standardized in modern Java, does not fall through.
String mode = “maintenance”; switch (mode) { case “run”: System.out.println(“mode: production”); break; case “maintenance”: System.out.println(“mode: service”); break; default: System.out.println(“mode: unknown”); }
In Java 14 and later, arrow labels can make the same selection easier to read. Each arrow case handles one selected alternative without a trailing break.
switch (mode) { case “run” -> System.out.println(“mode: production”); case “maintenance” -> System.out.println(“mode: service”); default -> System.out.println(“mode: unknown”); }
Both examples print mode: service. A switch may also be an expression that returns a value. See the Java 21 switch documentation for arrow cases, yield, and exhaustiveness.
3. Repeat actions with for, while, and do-while
Choose a three-part for loop when a counter has a natural initialization, condition, and update. Choose while when repetition depends on a condition that may initially be false. Choose do-while when the body must execute at least once. The do-while condition ends with a semicolon.
for (int i = 0; i < 3; i++) { System.out.println(i); // 0, 1, 2 } int attempts = 0; while (attempts < 2) { attempts++; System.out.println(“attempt ” + attempts); } int checks = 0; do { checks++; System.out.println(“check ” + checks); } while (checks < 1);
A condition is checked before each for or while iteration, but after a do-while body. If the condition never becomes false, the program can loop forever. Plan how a program will stop, especially when interacting with external devices.
4. Enhanced for, continue, and break
An enhanced for loops over each value in an array or other iterable structure. It is concise when you need the value but not its numeric index. For arrays of primitive numbers, the iteration variable contains a copy of each element.
int[] readings = {40, 76, 92, 55}; for (int value : readings) { System.out.println(value); }
Use an indexed loop if you need both the reading and its position. continue skips the remaining statements in the current iteration. break exits the innermost enclosing loop or switch.
int[] readings = {40, 76, 92, 55}; for (int i = 0; i < readings.length; i++) { int value = readings[i]; if (value < 70) continue; System.out.printf(“sample %d: %d C%n”, i, value); if (value >= 90) { System.out.println(“STOP at critical sample”); break; } }
This displays samples 1 and 2 but skips sample 0 because it is below 70. The loop ends at sample 2 (value 92), so sample 3 is never processed. A labeled break can terminate a named outer loop, but ordinary code should use the simplest clear exit condition.
5. Compile the complete equipment-monitoring mini-lab
Create a file named Main.java. This full example combines conditionals, a modern arrow-style switch, indexed looping, continue, break, a while loop, and a do-while loop. The example was compiled and executed with OpenJDK 21; the values simulate a monitoring console, not real sensor measurements.
public class Main { public static void main(String[] args) { int temperature = 76; if (temperature >= 90) { System.out.println(“ALERT: critical heat”); } else if (temperature >= 70) { System.out.println(“INSPECT COOLING”); } else { System.out.println(“NORMAL”); } String mode = “maintenance”; switch (mode) { case “run” -> System.out.println(“mode: production”); case “maintenance” -> System.out.println(“mode: service”); default -> System.out.println(“mode: unknown”); } int[] readings = {40, 76, 92, 55}; for (int i = 0; i < readings.length; i++) { int reading = readings[i]; if (reading < 70) continue; System.out.printf(“sample %d: %d C%n”, i, reading); if (reading >= 90) { System.out.println(“STOP at critical sample”); break; } } int attempts = 0; while (attempts < 2) { attempts++; System.out.println(“attempt ” + attempts); } int checks = 0; do { checks++; System.out.println(“check ” + checks); } while (checks < 1); } }
Save, then run javac Main.java followed by java Main. Java compiles the Main class into bytecode, which the JVM executes. The exact tested output is:
INSPECT COOLING mode: service sample 1: 76 C sample 2: 92 C STOP at critical sample attempt 1 attempt 2 check 1
Notice that sample 0 never prints because of continue, and sample 3 never prints because of break. The while loop runs twice, while the do-while block runs once even though the final condition is false.
6. Common mistakes
- Missing parentheses: Java uses
if (condition), notif condition. - Accidental switch fallthrough: colon cases may need
break; arrow cases do not implicitly fall through. - Off-by-one bounds: a four-item array has indices 0–3. Use
i < array.length, noti <= array.length. - Infinite while loop: modify the state that the termination condition depends on.
- Confusing continue and break:
continueadvances to the next iteration;breakexits. - Misreading an enhanced for: use an indexed loop when element positions or writes to primitive arrays matter.
7. Practice and self-check
- Change the first temperature to 65. Which message is printed?
- Change
modetorun. Does the arrow switch execute the maintenance case? - Replace
breakwithcontinuewhen a reading reaches 90. What changes in the sample output? - Modify the while-loop limit to 3 and predict the number of attempt messages.
- Explain why
do-whileprints once whenchecks < 1becomes false immediately afterward. - Write an enhanced
forloop to calculate the total of all four readings.
Answer guide: (1) NORMAL; (2) no, only production prints; (3) sample 3 is examined on the next iteration but does not print because it is below 70; (4) three; (5) its condition is tested after the first execution; (6) total = 263.
Official documentation and next steps
Use Dev.java: Controlling the Flow, the Oracle Java Control Flow tutorial, and the Java switch reference to verify language behavior. Compare OSGo.004 and OSC.005 to see how related loop ideas differ across languages. The next Java track lesson can introduce methods, parameters, return values, and method overloading. The complete curriculum rotation next moves to JavaScript.
Editor’s Note: We volunteer daily to ensure the credibility of the information on this platform is Verifiably True. If you would like to support our work and help further secure the integrity of our research initiatives, please scan the QR code below to donate 5,000 sats.

For mobile scanning, open the lesson on a larger screen and scan the QR code with a compatible Bitcoin wallet. Verify the destination address before sending: 3C9o19EH5HSiwEPyCTmEKzxhNCbo2X6TTb.
BitcoinVersus.tech is not a financial advisor. This media platform reports on financial subjects purely for informational purposes.

Leave a Reply