Iterations and loops. They matter because code would be impossibly long if you had to write the same instruction 50 times manually. Loops automate repetition, letting you process collections, validate user input, and control how many times a block runs — all essential for passing the 1Z0-829 exam.
Jump to a section
A simple way to picture Iterations and Loops
3 loads of laundry sit in your basket waiting to be folded. You have a rule: pick up one item, fold it, put it in the drawer, and repeat until the basket is empty. Your hand reaches in, grabs a shirt, folds it, stashes it, then goes back for socks. That reach-fold-store-repeat cycle is a loop. The basket is your data, your hand is the loop variable, and the empty drawer is the stopping condition. If you forget to check whether the basket is empty, you will keep reaching into thin air forever — that is an infinite loop. 10 pairs of socks might match a special rule: if you find a pair, roll them together before storing. That is a conditional inside the loop, like an if statement. Nested loops appear when you have a drawer with compartments: for each compartment, you fold all items inside it before moving to the next. The practical limit is that you cannot fold more items than the basket holds — that is the loop boundary. Every laundry session ends when the basket is empty, just as every good loop ends when its condition fails. This mental picture maps directly to while, for, and for-each loops in Java, where you control exactly how many times the work repeats.
A loop is a structure that repeats a block of code until a condition becomes false. Think of a condition as a yes-or-no question that Java asks before each repetition: Should I run this block again? If the answer is yes, the block executes. If no, Java skips it and moves on. Java provides four loop types: while, for, for-each, and do-while. The exam focuses on the first three plus nested loops.
A while loop checks its condition first. If the condition is true, the body runs. Then Java checks again. If the condition is false from the start, the body never runs. The structure is: while (condition) { body }. This is ideal when you do not know in advance how many times you need to repeat, such as reading data until a file ends.
A for loop packs initialisation, condition, and update into one line. The structure is: for (initialisation; condition; update) { body }. The initialisation runs once at the start. The condition is checked before each iteration. The update runs after each iteration. A typical example is counting to 10: for (int i = 1; i <= 10; i++) { System.out.println(i); }. The variable i starts at 1, the condition i <= 10 is true, so the body prints 1. Then i++ increments i to 2, condition checked again, and so on until i becomes 11, at which point the condition is false and the loop ends.
A for-each loop is a simplified version of the for loop used exclusively for iterating over arrays or collections. Its structure is: for (Type variableName : arrayOrCollection) { body }. For example, if you have an array of names, you write for (String name : names) { System.out.println(name); }. Java automatically takes each element one by one and assigns it to name. You do not manage an index or a counter. The for-each loop cannot modify the array while iterating without risking a ConcurrentModificationException, but it is the safest and clearest way to read every element.
Nested loops happen when one loop sits inside another. For each iteration of the outer loop, the inner loop runs completely from start to end. These are useful for working with two-dimensional data, like a grid of seats in a cinema. If you want to print every seat row and column, you would use for (int row = 0; row < 10; row++) { for (int col = 0; col < 20; col++) { print seat; } }. The inner loop runs all 20 columns for each of the 10 rows, giving 200 print operations.
The break statement exits the current loop immediately, skipping any remaining iterations. The continue statement skips the rest of the current iteration and jumps to the next condition check. Both can be used with labels to break or continue an outer loop from inside an inner loop. A label is just a name followed by a colon placed before a loop, like outerLoop: for (int i = 0; i < 3; i++). Then you can write break outerLoop; to exit both loops at once.
Iterations replace manual repetition. Without loops, processing a thousand customer records would require writing the same code a thousand times. Loops make the code shorter, easier to read, and less error-prone. The exam tests your ability to trace loop execution, identify infinite loops, and understand the exact flow with break and continue.
Initialise Loop Variable
Set the starting value for the variable that will control how many times the loop runs. In a for loop, this happens in the first part of the header, for example int i = 0. In a while loop, you must declare and assign the variable before the loop starts.
Evaluate Condition
Java checks the boolean condition inside the parentheses. If the condition is true, the loop body executes. If false, the loop ends and control moves to the next statement after the loop. This step happens at the start of every iteration for while and for loops.
Execute Loop Body
The code inside the loop braces runs. This can include any valid Java statements, such as calculations, method calls, or even other loops. During this step, break and continue can alter the flow.
Execute Update Expression
In a for loop, after the body completes, the update expression runs. This typically increments or decrements the loop variable. Then the condition is re-evaluated. This step does not exist in a while loop; the condition relies on changes made inside the body.
Re-evaluate Condition
Java checks the condition again with the updated variable. If it is still true, the body runs again. This cycle repeats until the condition becomes false, at which point the loop exits entirely.
A junior developer at a retail company is asked to update the stock levels for every product in a list of 5,000 items. Without loops, they would need to write 5,000 nearly identical lines of code. Instead, they open the IDE and write a for loop that reads each product ID from an array, queries the database for the current stock, subtracts the day's sales, and writes back the new value. The loop runs exactly 5,000 times, once per product.
In a real development sprint, loops appear in almost every feature:
Processing user input until the user types 'exit'
Sending personalised emails to every customer in a mailing list
Validating every field in a submitted form
Calculating totals for each item in a shopping cart
Generating report rows for a monthly sales summary
The scenario becomes more interesting when a bug arises. Suppose the developer forgets to increment the loop counter in a while loop that processes database rows. The condition never changes, so the loop runs forever, crashing the application. The senior developer reviews the code, spots the missing increment, and fixes it. This exact mistake is a frequent exam trap.
Another real-world use is iterating over a collection of user accounts and checking each one for expiration. A for-each loop reads each account object, checks the expiry date, and if expired, adds the account to a deactivation list. The developer uses continue to skip accounts that are already inactive, avoiding redundant checks. This pattern shows how continue optimises performance by skipping unnecessary work.
Nested loops are common when processing data from a spreadsheet. If the spreadsheet has 10 rows and 15 columns, an outer loop iterates through rows and an inner loop iterates through columns for each row. The developer might use a label with break to stop processing a row early if a mandatory field is missing. This prevents partial updates and keeps data consistent.
The 1Z0-829 exam tests your precise understanding of loop mechanics, not your ability to write creative code. You will see multiple-choice questions that ask: What is the output? How many times does this loop execute? Does it compile? The examiners set traps around:
Off-by-one errors in loop conditions
Using break and continue with labels
The difference between for and for-each
Nested loop iteration counts
Infinite loop scenarios
Trap 1: The condition uses '<=' instead of '<', or vice versa. For example, for (int i = 0; i <= 10; i++) runs 11 times, not 10. Beginners often miscount. The exam expects you to count iterations accurately.
Trap 2: Placing a semicolon immediately after the loop header, like for (int i = 0; i < 5; i++); This creates an empty loop body. The following block of code runs only once, not five times. The exam loves this.
Trap 3: Using continue inside a for loop and forgetting that the update expression runs after continue. The continue skips the rest of the body but does not skip the increment step. Many candidates think continue jumps directly to the condition check, but in a for loop the update expression runs first.
Trap 4: The for-each loop cannot modify the underlying array or collection while iterating. If you try to remove an element from a List inside a for-each loop without using an Iterator, the code throws a ConcurrentModificationException. The exam questions will show code that does this and ask whether it compiles or what exception is thrown.
Key definitions to memorise:
Loop variable: the variable that controls loop termination
Iteration: one complete execution of the loop body
Infinite loop: a loop whose condition never becomes false
Label: an identifier followed by a colon used to mark a loop for targeted break or continue
Off-by-one: error where loop runs one too many or one too few times
The exam also tests nested loops with break and continue targeting outer loops. A question might show: outer: for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (j == 1) break outer; } } and ask how many times the inner loop runs. The answer is 1 iteration because the break outer exits both loops immediately.
Memorise the exact syntax for each loop type. The while loop requires parentheses around the condition and braces for the body. The for loop requires three parts separated by semicolons. The for-each uses a colon, not a semicolon, between the variable declaration and the collection name.
A while loop checks its condition before each iteration and may never execute the body if the condition is initially false.
A for loop combines initialisation, condition, and update in a single line and is best when the number of iterations is known in advance.
A for-each loop iterates over every element in an array or collection without needing an index variable.
The break statement exits the innermost loop immediately, unless a label directs it to an outer loop.
The continue statement skips the rest of the current iteration and jumps to the next condition check.
Placing a semicolon directly after a loop header creates an empty loop body, causing the intended block to execute only once.
In nested loops, the inner loop runs completely for each iteration of the outer loop, leading to multiplication of total iterations.
Using break with a label allows exiting multiple levels of nested loops in one statement.
These come up on the exam all the time. Here's how to tell them apart.
while loop
Condition checked before first execution
No built-in initialisation or update syntax
Ideal when iteration count unknown
for loop
Combines initialisation, condition, update in one line
Update expression runs after each iteration automatically
Ideal when iteration count known
for loop
Requires explicit index variable
Can modify array elements by index
Works with any iterable including arrays
for-each loop
No index variable needed
Cannot modify array or collection structure during iteration
Syntactic sugar for reading all elements
break
Exits the loop immediately
Can be used with a label to exit outer loops
Skips all remaining iterations entirely
continue
Skips only the current iteration
Cannot skip outer loops without label
Continues to next iteration of the same loop
nested loop
One loop inside another
Inner loop runs completely for each outer iteration
Total iterations = product of both loop counts
single loop
Only one loop level
Runs a linear number of iterations
Simpler to trace and debug
Mistake
In a for loop, the update expression runs after the condition check but before the body executes.
Correct
The update expression runs after the body executes and before the next condition check.
New programmers often read the for header left to right and assume the update happens before the body. The actual order is initialisation, condition check, body, update, condition check, body, update, and so on.
Mistake
The break statement always exits the innermost loop only.
Correct
By default, break exits the innermost loop, but with a label it can exit any enclosing loop.
Many learners see break used inside nested loops and assume it always breaks one level. The exam explicitly tests label usage, which allows breaking multiple levels.
Mistake
A for-each loop can be used to modify the elements of the array it iterates over.
Correct
A for-each loop cannot modify the array or collection structure. You can change the properties of objects within the array, but you cannot add, remove, or replace elements without causing an exception.
The for-each loop hides the iterator, so beginners assume they have direct write access. The loop variable is a copy of the reference, not the reference itself in the case of primitives.
Mistake
The do-while loop always runs the body at least once, so it is the same as a while loop with the condition placed after the body.
Correct
That is actually correct for the behaviour, but the do-while loop is a distinct syntax. The exam treats them separately and tests the specific guarantee that the body runs at least once regardless of the condition.
Some beginners think do-while is just a while loop written differently, but the different semantic guarantee (at least one execution) is a key test point.
Mistake
Using continue in a while loop skips the condition check and jumps straight to the next iteration.
Correct
Continue skips the rest of the current iteration and jumps to the condition check. In a while loop, the condition is re-evaluated after continue.
The behaviour of continue in while loops is similar to for loops but the update step is missing in while loops. The exam uses this nuance to trick candidates who apply the for loop logic incorrectly.
Reveal each answer, then mark whether you got it right. Score 60%+ to unlock the next chapter.
A while loop checks the condition first, so its body may never run. A do-while loop runs the body at least once before checking the condition.
Yes, the for-each loop works with both arrays and collections that implement Iterable. It iterates over each element automatically.
The semicolon creates an empty loop body. The loop will run the expected number of times but do nothing, and the block of code following the loop will run only once.
You place a label before the outer loop, such as outerLoop: for (...), and then use break outerLoop; inside the inner loop.
No. Continue skips the rest of the current iteration but the update expression still runs immediately after the continue statement.
An infinite loop is a loop whose condition never becomes false, causing it to run forever. Avoid it by ensuring the condition eventually changes, such as incrementing a counter.
You've finished Iterations and Loops. Continue through the 1Z0-829 study guide to build a complete picture of the exam.
Done with this chapter?