Master loops in Java including for, while, do-while, enhanced for loops, break, continue, and labeled statements for the OCP 21 exam.
Table of Contents
1. The for Loop
The for
loop is used when you know how many times you want to execute a block of code.
1.1 Basic Syntax
for (initialization; condition; update) { // code to execute }
1.2 Examples
// Basic for loop for (int i = 0; i < 10; i++) { System.out.println(i); } // Counting backwards for (int i = 10; i > 0; i--) { System.out.println(i); } // Multiple variables for (int i = 0, j = 10; i < j; i++, j--) { System.out.println("i:" + i +", j:" + j); } // Step by 2 for (int i = 0; i < 10; i += 2) { System.out.println(i); // 0, 2, 4, 6, 8 } // Variables declared outside int i; for (i = 0; i < 5; i++) { System.out.println(i); } System.out.println("Final value:" + i); // 5
1.3 For Loop Components
- Initialization: Executed once before the loop starts
- Condition: Checked before each iteration; loop continues if true
- Update: Executed after each iteration
for (;;)
. 2. Enhanced for Loop (for-each)
The enhanced for loop (introduced in Java 5) simplifies iterating over arrays and collections.
2.1 Basic Syntax
for (type variable : iterable) { // code to execute }
2.2 Examples
// Iterating over array int[] numbers = {1, 2, 3, 4, 5}; for (int num : numbers) { System.out.println(num); } // Iterating over List List<String> names = List.of("Alice","Bob","Charlie"); for (String name : names) { System.out.println(name); } // Iterating over Set Set<Integer> set = Set.of(10, 20, 30); for (Integer value : set) { System.out.println(value); } // Iterating over Map (entrySet) Map<String, Integer> map = Map.of("a", 1,"b", 2,"c", 3); for (Map.Entry<String, Integer> entry : map.entrySet()) { System.out.println(entry.getKey() +":" + entry.getValue()); } // Iterating over Map (keySet) for (String key : map.keySet()) { System.out.println(key +":" + map.get(key)); } // Iterating over Map (values) for (Integer value : map.values()) { System.out.println(value); }
2.3 Limitations
- Cannot modify the collection/array during iteration (may throw ConcurrentModificationException)
- No access to the index (use traditional for loop if needed)
- Cannot iterate backwards
- Works with arrays and objects implementing
Iterableinterface
3. The while Loop
The while
loop executes a block of code as long as a condition is true.
3.1 Basic Syntax
while (condition) { // code to execute }
3.2 Examples
// Basic while loop int count = 0; while (count < 5) { System.out.println(count); count++; } // Reading input until condition Scanner scanner = new Scanner(System.in); int number; while ((number = scanner.nextInt()) != 0) { System.out.println("You entered:" + number); } // Processing until empty List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("C"); while (!list.isEmpty()) { String item = list.remove(0); System.out.println("Removed:" + item); } // Infinite loop (with break) while (true) { // do something if (someCondition) { break; } }
4. The do-while Loop
The do-while
loop is similar to while, but it executes the code block at least once before checking the condition.
4.1 Basic Syntax
do { // code to execute } while (condition);
4.2 Examples
// Basic do-while loop int count = 0; do { System.out.println(count); count++; } while (count < 5); // Menu-driven program Scanner scanner = new Scanner(System.in); int choice; do { System.out.println("1. Option 1"); System.out.println("2. Option 2"); System.out.println("0. Exit"); System.out.print("Enter choice:"); choice = scanner.nextInt(); switch (choice) { case 1 -> System.out.println("Option 1 selected"); case 2 -> System.out.println("Option 2 selected"); case 0 -> System.out.println("Exiting..."); default -> System.out.println("Invalid choice"); } } while (choice != 0); // At least one execution int x = 10; do { System.out.println("This executes at least once"); x++; } while (x < 5); // Condition is false, but code executed once
4.3 while vs do-while
| Aspect | while | do-while |
|---|---|---|
| Condition Check | Before execution | After execution |
| Minimum Executions | 0 (may not execute) | 1 (always executes at least once) |
| Use Case | When condition may be false initially | When you need at least one execution |
5. Nested Loops
Loops can be nested inside other loops to create complex iteration patterns.
5.1 Examples
// Multiplication table for (int i = 1; i <= 5; i++) { for (int j = 1; j <= 5; j++) { System.out.print(i * j +"\t"); } System.out.println(); } // Pattern printing for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i; j++) { System.out.print("*"); } System.out.println(); } // 2D array iteration int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { System.out.print(matrix[i][j] +""); } System.out.println(); } // Enhanced for with nested loops for (int[] row : matrix) { for (int value : row) { System.out.print(value +""); } System.out.println(); }
6. Break Statement
The break
statement terminates the loop or switch statement immediately.
6.1 Break in Loops
// Breaking out of loop for (int i = 0; i < 10; i++) { if (i == 5) { break; // Exits the loop when i equals 5 } System.out.println(i); // Prints 0, 1, 2, 3, 4 } // Searching in array int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int target = 5; boolean found = false; for (int num : numbers) { if (num == target) { found = true; break; // Stop searching once found } } if (found) { System.out.println("Found:" + target); } // Breaking from while loop int count = 0; while (true) { System.out.println(count); count++; if (count >= 5) { break; // Exit infinite loop } }
6.2 Break in Nested Loops
// Break only exits inner loop for (int i = 0; i < 3; i++) { for (int j = 0; j < 5; j++) { if (j == 3) { break; // Only breaks inner loop } System.out.print("i=" + i +" j=" + j +""); } System.out.println(); } // Output: i=0 j=0 i=0 j=1 i=0 j=2 // i=1 j=0 i=1 j=1 i=1 j=2 // i=2 j=0 i=2 j=1 i=2 j=2
7. Continue Statement
The continue
statement skips the rest of the current iteration and proceeds to the next iteration.
7.1 Examples
// Skipping even numbers for (int i = 0; i < 10; i++) { if (i % 2 == 0) { continue; // Skip even numbers } System.out.println(i); // Prints 1, 3, 5, 7, 9 } // Processing only valid items List<String> items = List.of("apple","","banana", null,"cherry"); for (String item : items) { if (item == null || item.isEmpty()) { continue; // Skip invalid items } System.out.println("Processing:" + item); } // Continue in while loop int count = 0; while (count < 10) { count++; if (count % 3 == 0) { continue; // Skip multiples of 3 } System.out.println(count); // Prints 1, 2, 4, 5, 7, 8, 10 }
7.2 Continue vs Break
| Statement | Effect |
|---|---|
| break | Exits the loop completely |
| continue | Skips to next iteration |
8. Labeled Statements
Labels allow break
and continue
to target specific loops in nested structures.
8.1 Labeled Break
// Breaking outer loop from inner loop outer: for (int i = 0; i < 3; i++) { inner: for (int j = 0; j < 5; j++) { if (i == 1 && j == 2) { break outer; // Breaks outer loop, not just inner } System.out.print("i=" + i +" j=" + j +""); } System.out.println(); } // Output: i=0 j=0 i=0 j=1 i=0 j=2 i=0 j=3 i=0 j=4 // i=1 j=0 i=1 j=1 // Searching in 2D array int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int target = 5; boolean found = false; search: for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { if (matrix[i][j] == target) { found = true; break search; // Exit both loops } } }
8.2 Labeled Continue
// Continuing outer loop from inner loop outer: for (int i = 0; i < 3; i++) { inner: for (int j = 0; j < 3; j++) { if (i == 1 && j == 1) { continue outer; // Continues outer loop, skips rest of inner } System.out.print("i=" + i +" j=" + j +""); } System.out.println(); } // Output: i=0 j=0 i=0 j=1 i=0 j=2 // i=1 j=0 // i=2 j=0 i=2 j=1 i=2 j=2
9. Common Pitfalls
9.1 Infinite Loops
// WRONG: Condition never becomes false int i = 0; while (i < 10) { System.out.println(i); // Missing i++ - infinite loop! } // CORRECT: Update the variable int i = 0; while (i < 10) { System.out.println(i); i++; // Update condition }
9.2 Modifying Collection During Iteration
List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("C"); // WRONG: Modifying during iteration for (String item : list) { if (item.equals("B")) { list.remove(item); // ConcurrentModificationException! } } // CORRECT: Use Iterator or traditional for loop Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { String item = iterator.next(); if (item.equals("B")) { iterator.remove(); // Safe removal } }
9.3 Off-by-One Errors
int[] arr = {1, 2, 3, 4, 5}; // WRONG: ArrayIndexOutOfBoundsException for (int i = 0; i <= arr.length; i++) { System.out.println(arr[i]); } // CORRECT: Use < instead of <= for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); }
10. Exam Key Points
Critical Concepts for OCP 21 Exam:
- for Loop:
for (init; condition; update), all components optional - Enhanced for Loop:
for (type var : iterable), works with arrays and Iterable - while Loop: Checks condition before execution, may execute 0 times
- do-while Loop: Checks condition after execution, executes at least once
- break Statement: Exits the loop immediately
- continue Statement: Skips to next iteration
- Labeled Statements: Use labels to break/continue outer loops
- Nested Loops: Loops can be nested, break/continue affect innermost loop by default
- Loop Variables: Variables declared in for loop are scoped to the loop
- Infinite Loops:
Can be created with
for (;;)orwhile (true) - Collection Modification: Don't modify collections during enhanced for iteration
- Array Length:
Use
array.length, notarray.length() - Off-by-One:
Be careful with loop bounds (
<vs<=) - Loop Control: break exits loop, continue skips to next iteration
- Label Syntax:
labelName:before loop,break labelName;to target
0 Comments