Study guide
2.4 Loops and Branching Statements
Oracle Java SE 21 Developer 1Z0-830
Track your progress as you read
Finished sections get a check mark.
1 Chapter 1: Java Basics, Primitive Types, and Operators
1.1 Program Structure, Primitives, Literals, Scopes, and var 1.2 Operators, Precedence, and Type Casting 1.3 Strings, Text Blocks, and StringBuilder 1.4 Date and Time APIs (java.time)
2 Chapter 2: Controlling Program Flow & Pattern Matching
2.1 Conditional Logic: if-else and Ternary Operators 2.2 Switch Statements and Switch Expressions 2.3 Pattern Matching for switch and instanceof 2.4 Loops and Branching Statements
3 Chapter 3: Object-Oriented Design & Class Architecture
3.1 Class Declarations, Constructors, and Object Lifecycle 3.2 Encapsulation and Access Modifiers 3.3 Inheritance, Method Overriding, and Polymorphism 3.4 Abstract Classes and Interfaces 3.5 Nested, Inner, Local, and Anonymous Classes 3.6 Method Overloading, Overload Resolution, and Varargs
4 Chapter 4: Modern Java Data Modeling: Records, Enums, and Sealed Types
4.1 Java Records, Canonical/Compact Constructors, and Component Accessors 4.2 Java Enums: Fields, Methods, and Abstract Constant-Specific Behavior 4.3 Sealed Classes and Interfaces: permits, final, non-sealed, and Hierarchy Architecture 4.4 Advanced Record Patterns (JEP 440), Nested Deconstruction, and Sealed Hierarchy Exhaustiveness
5 Chapter 5: Exception Handling and Annotations
5.1 Exception Hierarchy: Checked vs. Unchecked Exceptions 5.2 Exception Handling: try, catch, finally, and Multi-Catch 5.3 Resource Management: try-with-resources and AutoCloseable 5.4 Custom Exceptions and Best Practices 5.5 Java Annotations: Built-in, Meta-Annotations, and Custom Types
6 Chapter 6: Generics and the Collections Framework
6.1 Generics Fundamentals and Generic Methods 6.2 Wildcards, Type Bounds, and Type Erasure 6.3 Core Collections: Lists, Sets, Queues, and Maps 6.4 Sequenced Collections in Java 21 6.5 Sorting, Comparable, and Comparator 6.6 Arrays: Creation, Multidimensional Forms, and the Arrays Utility Class
7 Chapter 7: Functional Programming & Lambda Expressions
7.1 Built-in Functional Interfaces in java.util.function 7.2 Lambda Expressions, Variable Scopes, and Effectively Final 7.3 Method References: Four Varieties and Edge Cases 7.4 Working with java.util.Optional
8 Chapter 8: The Stream API and Data Pipelines
8.1 Stream Creation and Intermediate Operations 8.2 Terminal Operations and Reductions 8.3 Advanced Collectors, Grouping, Partitioning, and Teeing 8.4 Primitive Streams and Parallel Stream Processing
9 Chapter 9: Concurrency, Multithreading, and Virtual Threads
9.1 Thread Fundamentals, Creation, and Lifecycle 9.2 Thread Safety, Synchronization, and the Java Memory Model 9.3 Concurrency Utilities: ExecutorService, Callable, and Future 9.4 Concurrent Collections, Atomics, and Explicit Locks 9.5 Virtual Threads in Java 21 (Carrier Threads, Pinning, and Best Practices)
10 Chapter 10: The Java Platform Module System (JPMS)
10.1 Module Architecture and module-info.java Declarations 10.2 Module Directives: requires, exports, opens, provides, and uses 10.3 Modular Compilation, Packaging, and CLI Execution 10.4 Module Types, Migration Strategies, ServiceLoader SPI, and JLink
11 Chapter 11: Java I/O, NIO.2, and Object Serialization
11.1 Classic Java I/O Streams and Readers/Writers 11.2 Java NIO.2 File API: Path, Paths, and File System Operations 11.3 Advanced NIO.2 Stream Operations and Directory Traversal 11.4 Java Object Serialization and Record Serialization
12 Chapter 12: Implementing Localization and Internationalization
12.1 Locales and Resource Bundles 12.2 Formatting and Parsing Numbers, Currencies, Dates, Times, and Messages
2.4 Loops and Branching Statements
Key Takeaways Explain This Topic AI
while loops evaluate termination conditions at loop entry, whereas do-while loops evaluate conditions at exit, guaranteeing at least one body execution.
Classic for loop headers allow multiple comma-separated initializations of the same type and multiple comma-separated update statements.
The enhanced for-each loop iterates over arrays and Iterable objects but forbids structural modification of collections during traversal.
Labeled break and continue statements permit precise transfer of control across nested loops and labeled statement blocks.
Last updated: September 2026
Looping Statements and Branching Constructs
Iteration and jumping control constructs allow Java programs to execute code repeatedly and alter execution flow. For the Oracle Certified Professional: Java SE 21 Developer (1Z0-830) exam, candidates must master the precise semantics of all four loop types ( while , do-while , traditional for , and enhanced for-each ), labeled break and continue statements, and Java's rigorous compile-time reachability rules.
- 1. The Four Looping Constructs
- The while Loop
A while loop evaluates its boolean condition prior to executing the loop body: while (booleanExpression) { statement; }
If the condition is initially false , the body executes zero times .
Reachability Rule : If the condition is the literal false , the compiler flags the body as unreachable code and generates a compile-time error: // while (false) { System.out.println("Unreachable"); } // COMPILE ERROR! Unreachable code
boolean flag = false;
while (flag) { System.out.println("Reachable compile-time check"); } // Compiles cleanly!
The do-while Loop
A do-while loop executes its body first, then evaluates the condition at the end of each iteration: do { statement; } while (booleanExpression);
Guarantees at least one execution of the loop body.
Note the required trailing semicolon ; after while(condition); .
Variable Scope in Condition : Variables declared inside the do block are out of scope in the while conditional check: do {
- int counter = 1;
- System.out.println(counter);
- } while (counter < 5); // COMPILE ERROR: cannot find symbol 'counter'
- 2. Classic for Loops and Enhanced for-each
- Classic for Loop Anatomy
A classic for loop contains three header sections separated by semicolons: for (initialization; condition; update) { statement; } for (int i = 0, j = 10; i < j; i++, j--) {
- System.out.println(i + " " + j);
- }
Initialization Section Rules :
You can declare multiple variables, but they must share the same data type : for (int i = 0, j = 10; i < 5; i++) {} // Legal: both are int
// for (int i = 0, long j = 10; i < 5; i++) {} // COMPILE ERROR: multiple type declarations
If variables are declared prior to the loop, you can initialize variables of different types using comma-separated assignment expressions: int i;
long j;
for (i = 0, j = 10L; i < 5; i++) {} // Legal assignment expressions!
Termination Condition Section Rules :
Must evaluate to a boolean or Boolean .
Optional: If omitted, it defaults to true (creating an infinite loop: for (;;) {} ).
Update Section Rules :
Can contain zero or more comma-separated expression statements (e.g., i++, j-- , method invocations).
Side effects inside update expressions take place at the end of each iteration before the next condition check.
Enhanced for-each Loop
The enhanced for loop provides clean, read-oriented traversal over arrays and objects implementing java.lang.Iterable<T> (such as List , Set , Queue ): for (ElementType variable : expression) { statement; } String[] fruits = {"Apple", "Banana", "Cherry"};
- for (String fruit : fruits) {
- System.out.println(fruit);
- }
Enhanced for-each Compilation & Traps:
Target Type Compatibility : The target expression must evaluate to an array or a type implementing java.lang.Iterable<T> . Passing a java.util.Map directly causes a compile-time error because Map does not implement Iterable (you must iterate over map.keySet() , map.values() , or map.entrySet() ).
Underlying Desugaring :
For an array T[] arr , the compiler generates an indexed loop: for (int i = 0; i < arr.length; i++) { T var = arr[i]; ... } .
For an Iterable<T> coll , the compiler generates an iterator loop: for (Iterator<T> it = coll.iterator(); it.hasNext(); ) { T var = it.next(); ... } .
No Array Mutation via Primitive Iteration Variable : In primitive arrays, assigning a new value to the iteration variable only modifies the local copy and does not alter the array element: int[] numbers = {1, 2, 3};
for (int n : numbers) {
n = n * 2; // Only modifies local copy 'n'!
}
System.out.println(numbers[0]); // Still prints 1!
ConcurrentModificationException : Modifying the size of a collection (such as list.add(...) or list.remove(...) ) while iterating over it in an enhanced for loop causes the underlying Iterator to detect a structural modification mismatch and throw a ConcurrentModificationException at runtime.
3. Branching Statements: break , continue , and Labels
Java provides jump statements to alter iterative execution:
break Statement
Unlabeled break : Terminates the innermost enclosing for , while , do-while , or switch construct and transfers control to the statement immediately following it.
Labeled break LABEL : Terminates the statement or block identified by LABEL . The target can be any labeled statement or block {} , not only a loop! BLOCK_A: {
- System.out.println("Start Block A");
- if (true) break BLOCK_A; // Legal: breaks out of labeled block
- System.out.println("End Block A"); // Skipped
- }
- System.out.println("After Block A");
- continue Statement
Unlabeled continue : Skips the remaining statements in the current iteration of the innermost enclosing loop and advances to the update step (in for ) or condition check (in while / do-while ).
Labeled continue LABEL : Skips the remaining statements of the current iteration of the enclosing labeled loop and advances to the update/condition step of that outer loop.
Restriction : continue can ONLY be used inside a loop construct. Using continue inside a switch (outside a loop) or labeled non-loop block is a compile-time error. OUTER: for (int i = 1; i <= 3; i++) {
- INNER: for (int j = 1; j <= 3; j++) {
- if (i == 2 && j == 2) {
continue OUTER; // Jumps directly to i++ in OUTER loop!
- }
- System.out.print(i + "" + j + " ");
- }
- }
- // Output: 11 12 13 21 31 32 33
- 4. Loop Architecture and Behavior Comparison
- Loop Type Condition Evaluation Point Minimum Iterations Common Use Case
- while Loop entry (pre-test) 0 When iteration count is unknown and condition may initially be false
- do-while Loop exit (post-test) 1 When loop body must execute at least once (e.g., user input validation)
- Classic for Loop entry (pre-test) 0 Counted loops with index variables and complex stepping
Enhanced for-each Implicit Iterator.hasNext() 0 Clean sequential traversal over Arrays and Iterable collections
5. Compiler Reachability and Dead Code Rules
The Java compiler rigorously enforces reachability (JLS §14.21). Any statement that can never be executed causes a compile-time error:
Statements After Unconditional Jumps : Statements immediately following an unconditional break , continue , return , or throw without a surrounding branch cause compilation errors: while (true) {
- break;
- // System.out.println("Unreachable"); // COMPILE ERROR: unreachable statement
- }
Infinite Loops and Trailing Code : An infinite loop created with constant condition while(true) or for(;;) makes code after the loop unreachable: while (true) {}
// System.out.println("Done"); // COMPILE ERROR: unreachable statement
while (false) vs. if (false) Exception :
while (false) { ... } -> COMPILE ERROR (Unreachable statement).
if (false) { ... } -> COMPILES SUCCESSFULLY (Special exemption in the JLS to support conditional compilation and debugging flags).
do { ... } while (false); -> COMPILES SUCCESSFULLY (Body executes once, condition checked at exit).