Study guide
2.3 Iteration Constructs, Loop Control, and Branching Labels
Oracle Java SE 17 Developer Certified Professional 1Z0-829
Track your progress as you read
Finished sections get a check mark.
1 Introduction: The 1Z0-829 Exam
About the Java SE 17 Developer (1Z0-829) Exam
2 Chapter 1: Java Fundamentals & Language Basics
1.1 Primitive Types, Literals, Wrapper Classes, and Type Promotion/Casting 1.2 Local Variable Type Inference (`var`) Rules and Scoping 1.3 Operators, Precedence, Evaluation Order, and Short-Circuit Evaluation 1.4 Text Blocks, String Immutability, and StringBuilder APIs
3 Chapter 2: Program Flow & Decision Constructs
2.1 Conditional Branching with if/else and the Ternary Operator 2.2 Switch Statements and Switch Expressions 2.3 Iteration Constructs, Loop Control, and Branching Labels
4 Chapter 3: Object-Oriented Design & Class Mechanics
3.1 Class Declarations, Field/Method Signatures, and Access Modifiers 3.2 Constructors, Overloading, Initialization Order, and Garbage Collection 3.3 Inheritance, Method Overriding, Polymorphism, and `super`/`this` 3.4 Abstract Classes, Static Members, and Object Methods (`equals`, `hashCode`, `toString`)
5 Chapter 4: Advanced OOP: Interfaces, Records & Sealed Types
4.1 Interface Architecture: Default, Static, and Private Methods 4.2 Enumerations: Constants, Constructors, Methods, and Custom Bodies 4.3 Records: Canonical/Compact Constructors, Components, and Immutability 4.4 Sealed Classes and Interfaces: `permits`, Hierarchy Constraints, and Modifiers
6 Chapter 5: Pattern Matching & Nested Types
5.1 Pattern Matching for `instanceof` and Flow Scoping Mechanics 5.2 Nested Types: Member Inner, Static Nested, Local, and Anonymous Classes 5.3 Defensive Programming, Immutability Patterns, and Validation
7 Chapter 6: Generics, Collections & Arrays
6.1 Generic Classes, Interfaces, Methods, and Type Erasure 6.2 Bounded Type Parameters and Wildcards (PECS Rule) 6.3 Collections Framework: List, Set, Queue, and Deque APIs 6.4 The Map Interface, Sorting, Comparable, and Comparator 6.5 Arrays: Declaration, Initialization, Multidimensional Arrays, and the Arrays Utility Class
8 Chapter 7: Functional Programming & Lambda Expressions
7.1 Functional Interfaces and Lambda Syntax Rules 7.2 Standard Functional Interfaces in `java.util.function` 7.3 Method References: Static, Bound, Unbound, and Constructor References
9 Chapter 8: The Stream API
8.1 Stream Lifecycle: Creation, Pipeline Architecture, and Lazy Evaluation 8.2 Intermediate Stream Operations: Filtering, Mapping, Sorting, and Slicing 8.3 Terminal Stream Operations: Reduction, Matching, Finding, and Collecting 8.4 Primitive Streams (`IntStream`, `LongStream`, `DoubleStream`) and Numeric Statistics
10 Chapter 9: Advanced Streams & Collectors
9.1 The Optional Class: Safe Null Handling, Transformation, and Chaining 9.2 The Collectors API: Downstream Reductions, Grouping, and Partitioning 9.3 Parallel Streams: Fork/Join Pool, Spliterators, and Concurrency Pitfalls
11 Chapter 10: Exception Handling
10.1 The Java Exception Hierarchy: Checked vs. Unchecked Exceptions and Errors 10.2 Exception Constructs: `try-catch-finally`, Multi-Catch, and Rethrowing 10.3 Try-With-Resources, `AutoCloseable`, Suppressed Exceptions, and Custom Exceptions
12 Chapter 11: Date/Time API & Localization
11.1 Date and Time Core Types: `LocalDate`, `LocalTime`, `LocalDateTime` 11.2 Timestamps, Intervals, and Durations: `Instant`, `Period`, and `Duration` 11.3 Time Zones, Daylight Saving Time (DST) Offsets, and `ZonedDateTime` 11.4 Internationalization and Localization: `Locale`, `ResourceBundle`, and Formatters 11.5 Formatting and Parsing Messages, Numbers, Percentages, and Localized Dates
13 Chapter 12: Java Platform Module System (JPMS)
12.1 Module Architecture, `module-info.java`, and Module Paths 12.2 Module Directives: `requires`, `requires transitive`, `exports`, and Qualified Exports 12.3 Reflection, Deep Encapsulation, `opens`, and Open Modules 12.4 Services in JPMS (`uses`, `provides...with`), Migration Paths, and Tooling (`jlink`, `jdeps`) 12.5 Compiling and Packaging Code: Non-Modular JARs, Modular JARs, and Migration Strategies
14 Chapter 13: Concurrency & Multithreading
13.1 Thread Fundamentals, `Runnable`, `Callable`, and Thread Lifecycle 13.2 Memory Visibility, `volatile`, Intrinsic Locks, and Synchronization 13.3 The Concurrency Framework: `ExecutorService`, Thread Pools, and `Future` 13.4 Concurrent Collections, Atomic Variables, Explicit Locks, and `CompletableFuture`
15 Chapter 14: Java I/O and NIO.2
14.1 Classical I/O: Byte and Character Streams, Readers, Writers, and Buffering 14.2 Object Serialization, `Serializable`, `transient`, and `serialVersionUID` 14.3 NIO.2 Architecture: `Path`, `Paths`, and Basic `Files` Operations 14.4 Advanced NIO.2: Directory Walking, Streams (`Files.lines`, `walk`), and `WatchService`
16 Chapter 15: Accessing Databases with JDBC
15.1 JDBC Architecture, Drivers, `DriverManager`, and `DataSource` Connections 15.2 SQL Execution: `Statement`, `PreparedStatement`, and `CallableStatement` 15.3 `ResultSet` Navigation, Data Types, and Transaction Management (Commit, Rollback, Savepoints)
17 Chapter 16: Annotations & the Java Logging API
16.1 Standard Annotations: @Override, @FunctionalInterface, @Deprecated, @SuppressWarnings, and @SafeVarargs 16.2 Java Logging API Basics: Logger, Levels, Handlers, and Configuration
2.3 Iteration Constructs, Loop Control, and Branching Labels
Key Takeaways Explain This Topic AI
The standard for loop header consists of initialization, termination condition, and update steps; multiple comma-separated variables may be initialized provided they all share the exact same data type.
The enhanced for-each loop traverses arrays and java.lang.Iterable objects; it cannot modify primitive array elements in place or structurally modify collections during iteration.
while loops evaluate their condition prior to the first iteration, whereas do-while loops execute their body at least once and must terminate with a trailing semicolon.
Java strictly forbids unreachable statements at compile time: the body of while (false) and any statement after an infinite loop with no break are compile errors, whereas if (false) is permitted for conditional compilation.
Labeled break terminates the designated labeled block or loop, while labeled continue skips the remainder of the current iteration and jumps to the update step of the designated labeled loop.
Last updated: October 2026
2.3 Iteration Constructs, Loop Control, and Branching Labels
Iteration constructs enable repetitive execution of statements until a termination condition is satisfied. Java SE 17 offers four primary loop constructs: the classic for loop, the enhanced for-each loop, the while loop, and the do-while loop. Navigating these constructs on the 1Z0-829 exam requires a precise understanding of header evaluation order, multi-variable initialization constraints, reachability analysis rules, and labeled flow control across nested loops.
The Classical for Loop Architecture
The standard for loop organizes iteration logic into three header expressions separated by semicolons: for (initialization; terminationCondition; updateExpression) {
- // Loop body
- }
- Execution Cycle
The Java Virtual Machine executes a standard for loop in a strict sequence:
Initialization : Executes exactly once when entering the loop.
Termination Condition : Evaluated before each iteration. If true , the body executes; if false , the loop terminates.
Loop Body : Executes.
Update Expression : Executes after the body finishes, immediately before the next condition check.
Cycle : Steps 2 through 4 repeat until the condition evaluates to false .
Multi-Variable Declarations and Syntax Rules
The initialization section allows declaring multiple variables separated by commas, but all declared variables must share the same type specifier : // Legal: i and j are both int
- for (int i = 0, j = 10; i < j; i++, j--) {
- System.out.println(i + ":" + j);
- }
- // COMPILE ERROR: cannot declare variables of different types in for header
- // for (int i = 0, long j = 10; i < 5; i++) { }
- If variables of differing types must be used, they must be declared prior to the loop header: int a = 0;
- long b = 100L;
- for (; a < 5; a++, b += 10) { // Legal: already declared
- System.out.println(a + " - " + b);
- }
- Optional Header Sections and Infinite Loops
All three components of the for loop header are optional:
Omitting the condition causes it to default to true .
The statement for (;;) { } creates an infinite loop identical to while (true) { } .
Variables declared in the initialization section have local block scope limited strictly to the header and body of the for loop. Attempting to access an initialized variable after the closing brace of the loop produces a compile-time error.
Enhanced for-each Loop Semantics and Traversal Constraints
Introduced in Java 5, the enhanced for loop simplifies sequential traversal over arrays and collections: for (ElementType variable : expression) {
- // Loop body
- }
- Target Requirements
The expression on the right-hand side of the colon must evaluate to:
A Java array ( T[] ).
An object implementing java.lang.Iterable<T> (such as List , Set , or Queue ).
Passing an arbitrary object or a java.util.Map directly to a for-each loop causes a compilation error (though iterating over map.keySet() , map.values() , or map.entrySet() is valid).
Mutation Limitations and Traps
Primitive Array Modification : The loop variable holds a copy of the current array element, not a reference to the array memory slot. Reassigning the loop variable does not modify the array: int[] numbers = {1, 2, 3};
- for (int n : numbers) {
- n = n * 10; // Modifies local variable n only
- }
System.out.println(numbers[0]); // Prints 1, NOT 10!
Structural Collection Modification : Altering the structure of a collection (invoking add() , remove() , or clear() ) while iterating via an enhanced for loop throws java.util.ConcurrentModificationException at runtime: List<String> names = new ArrayList<>(List.of("Alice", "Bob", "Charlie"));
- for (String name : names) {
- if (name.equals("Alice")) {
names.remove(name); // Throws ConcurrentModificationException on the next iteration!
- }
- }
Warning
The exception is thrown by the iterator's next next() call, not by remove() . If the removed element is the second-to-last one (for example, removing "Bob" from this three-element list), hasNext() returns false immediately and the loop ends silently without an exception, leaving [Alice, Charlie] . Use Iterator.remove() or removeIf() instead.
while vs. do-while Loops
The while and do-while loops differ primarily in the timing of condition evaluation: // Pre-test loop: condition checked before first iteration
- int count = 10;
- while (count < 5) {
- System.out.println("Never runs");
- }
- // Post-test loop: body guaranteed to execute at least once
- int total = 10;
- do {
- System.out.println("Executes once");
} while (total < 5); // Note: Trailing semicolon is mandatory!
Warning
Forgetting the trailing semicolon ; after the condition in a do-while construct is a common syntax trap that produces a compilation error.
Reachability Analysis and Unreachable Code Rules
The Java compiler enforces strict reachability rules governed by JLS §14.21. Any statement that cannot be executed under any circumstance causes a compile-time error , rather than a silent runtime omission.
Constant Conditions: while (false) vs. if (false)
A prominent exam topic is the asymmetric treatment of constant false conditions between while loops and if statements: // Legal: JLS explicitly allows if (false) to support conditional compilation
- if (false) {
- System.out.println("Dead code, but compiles");
- }
- // COMPILE ERROR: unreachable statement
- // while (false) {
- // System.out.println("Unreachable");
- // }
- Unreachable Statements Following Unconditional Transfers
Any statement immediately following an unconditional break , continue , return , or throw in the same block is unreachable and fails compilation: while (true) {
- break;
- // System.out.println("Hello"); // COMPILE ERROR: unreachable statement
- }
However, if an unreachable branch is guarded by a non-constant condition, the compiler allows it: boolean flag = false;
- while (flag) { // Compiles! flag is a variable, not a compile-time constant literal
- System.out.println("Compiles because flag is not final");
- }
- Branching Statements, Labeled Loops, and Evaluation Order
Java provides three unconditioned branching statements: break , continue , and return .
break : Exits the innermost loop or switch construct.
continue : Skips the remainder of the current iteration and jumps to the update step (in for ) or condition check (in while / do-while ).
Labeled Statements for Nested Flow Control
In deeply nested loops, an unlabeled break or continue only affects the innermost loop. Java allows prefixing any statement or loop with an identifier label (e.g., OUTER: ).
Labeled break : Terminates the entire statement or loop identified by the label.
Labeled continue : Aborts the current iteration and immediately begins the next iteration of the designated labeled loop. OUTER:
for (int i = 1; i <= 3; i++) {
INNER:
- for (int j = 1; j <= 3; j++) {
- if (i == 2 && j == 2) {
- break OUTER; // Exits both loops immediately
- }
- if (j == 1) {
- continue INNER; // Advances j to 2
- }
- System.out.print(i + "" + j + " ");
- }
- }
- // Outputs: 12 13
- Evaluation Order in Loop Conditions with Side Effects
- On the 1Z0-829 exam, loop conditions often contain increment ( ++ ) or decrement ( -- ) operators: int x = 0;
- while (x++ < 3) {
- System.out.print(x + " ");
- }
Tracing the evaluation:
x = 0 : Condition evaluates 0 < 3 ( true ), then x increments to 1 . Body prints "1 " .
x = 1 : Condition evaluates 1 < 3 ( true ), then x increments to 2 . Body prints "2 " .
x = 2 : Condition evaluates 2 < 3 ( true ), then x increments to 3 . Body prints "3 " .
x = 3 : Condition evaluates 3 < 3 ( false ), then x increments to 4 . Loop exits.
Final value of x after the loop is 4 . Total output: "1 2 3 " .
Comparison of Java Iteration Constructs
- Feature Standard for Enhanced for-each while do-while
- Minimum Executions 0 0 0 1
- Condition Check Timing Before each iteration Before each element Before each iteration After each iteration
- Index Access Direct counter available No built-in index counter Manual counter needed Manual counter needed
- Target Applicability Any conditional loop Arrays & Iterable only Any conditional loop Any conditional loop
- Header Variables Multiple of same type Single element variable None declared in header None declared in header
- Trailing Semicolon No No No Yes (mandatory after while(...) )