Jump Statements (break & continue) & Enhanced for Loop
break Statement ยท continue Statement ยท Labeled break/continue ยท Enhanced for-each Loop ยท Looping Strings ยท Prime Numbers ยท Fibonacci Series
Mastering fine-grained loop control and sequence traversal in Java: abruptly terminating loops with break, skipping iterations with continue, breaking out of deeply nested loops with labels, iterating arrays and collections cleanly with the enhanced for-each loop, and implementing Prime number tests and Fibonacci sequences.
1. Jump Statements: `break` vs `continue`
Java provides two jump statements to alter the natural execution cycle of loops:
+-----------------------------------------------------------------------------------+
| break vs continue IN LOOPS |
+-----------------------------------------------------------------------------------+
| 1. break STATEMENT: EMERGENCY EXIT |
| Immediately TERMINATES the entire enclosing loop and jumps to the code |
| following the loop's closing brace. |
+-----------------------------------------------------------------------------------+
| 2. continue STATEMENT: SKIP TO NEXT ROUND |
| Immediately SKIPS the remaining lines in the current iteration and jumps |
| directly to the loop's next update/condition evaluation. |
+-----------------------------------------------------------------------------------+Example Comparison:
for (int i = 1; i <= 5; i++) {
if (i == 3) break; // Loop stops completely when i is 3!
System.out.print(i + " "); // Prints: 1 2
}
for (int i = 1; i <= 5; i++) {
if (i == 3) continue; // Skips only number 3!
System.out.print(i + " "); // Prints: 1 2 4 5
}
2. Labeled `break` and `continue` (Nested Loop Control)
When working with nested loops, a standard break terminates only the innermost loop.
To break out of or continue an outer loop from within an inner loop, Java supports Labeled Statements:
outerLoop: for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
System.out.println("Breaking outer loop completely!");
break outerLoop; // Jumps completely out of BOTH loops!
}
System.out.println("i=" + i + ", j=" + j);
}
}3. The Enhanced `for-each` Loop (Java 5+)
The Enhanced for Loop (or for-each loop) provides a clean, readable syntax to iterate over arrays and collections without needing manual index variables (i) or boundary checks (array.length):
for (DataType element : collectionOrArray) {
// Access element directly
}String[] languages = { "Java", "Python", "Go", "Rust" };
// Traditional for loop:
for (int i = 0; i < languages.length; i++) {
System.out.println(languages[i]);
}
// Enhanced for-each loop (Clean & Modern):
for (String lang : languages) {
System.out.println(lang);
}
4. Prime Numbers & The Fibonacci Series
1. Prime Number Algorithm ($O(\sqrt{N})$ Optimization):
A Prime Number is a number $> 1$ divisible only by 1 and itself (e.g. 2, 3, 5, 7, 11, 13). - Optimization: Instead of checking all numbers up to $N$, we only need to test divisors up to $\sqrt{N}$ because factors repeat after the square root:boolean isPrime = (num > 1);
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break; // Found divisor, stop checking!
}
}2. The Fibonacci Sequence ($0, 1, 1, 2, 3, 5, 8, 13...$):
Each number is the sum of the two preceding numbers ($Fn = F{n-1} + F_{n-2}$):int first = 0, second = 1;
for (int i = 1; i <= count; i++) {
System.out.print(first + " ");
int next = first + second;
first = second;
second = next;
}Beginner Example & Code Anatomy
public class Main {
public static void main(String[] args) {
// 1. Break vs Continue Demonstration
System.out.println("=== 1. Continue Demo (Skip Even Numbers 1-10) ===");
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
System.out.print(i + " ");
}
System.out.println();
// 2. Enhanced For-Each Loop over Array
System.out.println("
=== 2. Enhanced For-Each Loop (Cloud Services) ===");
String[] cloudServices = { "AWS EC2", "Azure AppService", "GCP CloudRun", "Docker" };
for (String service : cloudServices) {
System.out.println("โ Deploying: " + service);
}
// 3. Generating Fibonacci Series (First 8 Terms)
System.out.println("
=== 3. Fibonacci Sequence (First 8 Terms) ===");
int terms = 8;
int t1 = 0, t2 = 1;
System.out.print("Series: ");
for (int step = 1; step <= terms; step++) {
System.out.print(t1 + " ");
int nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
System.out.println();
// 4. Prime Number Check
int testNumber = 29;
boolean isPrime = testNumber > 1;
for (int i = 2; i <= Math.sqrt(testNumber); i++) {
if (testNumber % i == 0) {
isPrime = false;
break;
}
}
System.out.println("
=== 4. Prime Number Test ===");
System.out.println("Is " + testNumber + " Prime? : " + isPrime);
}
}
๐ Line-by-Line Code Explanation
if (i % 2 == 0) continue;
Skips printing when i is even, proceeding directly to the next odd iteration.
for (String service : cloudServices)
Enhanced for-each loop directly binding each array element to the variable service without index notation.
int nextTerm = t1 + t2; t1 = t2; t2 = nextTerm;
Calculates the next Fibonacci term and shifts sliding window variables forward.
for (int i = 2; i <= Math.sqrt(testNumber); i++)
Optimized prime check evaluating divisors only up to square root of testNumber.
Practical Real-World Example
public class SearchAlgorithmEarlyExit {
public static void main(String[] args) {
String[] transactionIds = { "TXN_101", "TXN_102", "TXN_999_FRAUD", "TXN_104", "TXN_105" };
String targetFraud = "TXN_999_FRAUD";
boolean foundFraud = false;
System.out.println("--- Security Audit Log Scanning ---");
for (int i = 0; i < transactionIds.length; i++) {
System.out.println("Inspecting Transaction #" + (i + 1) + ": " + transactionIds[i]);
if (transactionIds[i].equals(targetFraud)) {
foundFraud = true;
System.out.println("๐จ ALERT: Fraudulent Transaction Detected at Index [" + i + "]!");
break; // Stop scanning further transactions immediately
}
}
System.out.println("Audit Complete. Scanner status: " + (foundFraud ? "QUARANTINED" : "CLEAN"));
}
}
- Attempting to modify array elements inside for-each loop: Writing "for (int x : array) { x = 0; }" modifies only the local copy variable x, NOT the actual array contents! Use standard index for loop for array mutations.
- Checking prime numbers up to N instead of sqrt(N): Testing "i < N" works but is O(N) slow. Using "i <= Math.sqrt(N)" runs in O(sqrt(N)) time.
- Confusing break with continue: "break" exits the entire loop; "continue" skips only the current iteration.
Test your understanding by writing the code directly in your editor or running in our online Java compiler:
// Coding Challenge:
// Write a program to find and print all Prime numbers between 1 and 50.
// Print in one line: "2 3 5 7 11 13 17 19 23 29 31 37 41 43 47"
public class Main {
public static void main(String[] args) {
// TODO: Print all prime numbers from 1 to 50
}
}
๐ก Frequently Asked Questions & Interview Insights
โ Can the enhanced for-each loop be used in reverse order?
No. The enhanced for loop only iterates forward from index 0 to length - 1. If reverse iteration is needed, use a standard index loop "for (int i = array.length - 1; i >= 0; i--)".
โ How do you iterate through characters in a String using enhanced for?
Call ".toCharArray()": "for (char c : str.toCharArray()) { System.out.println(c); }".
โ Why are labels rarely used in modern Java code?
Labeled breaks can make code harder to follow if overused (similar to "goto"). In clean code architecture, extracting nested loops into dedicated methods with "return" is preferred.
๐ Quick Chapter Recap
- break terminates loop immediately; continue skips to next iteration.
- Labeled break allows exiting outer nested loops directly.
- Enhanced for-each loop (for (T item : array)) provides clean read-only traversal.
- Prime checks are optimized by evaluating divisors up to Math.sqrt(N).