Loop Control: Continue Statement in Java

Introduction

Imagine you're sorting through a box of mixed fruits. When you find a rotten apple, you don't throw away the entire box—you just skip that one bad fruit and continue with the rest. The continue statement in Java does exactly this—it lets you skip the current iteration of a loop and immediately jump to the next one!

The continue statement is like a "fast-forward" button for loops. When certain conditions are met, it says "skip everything else in this iteration and move to the next one right away."


What is the Continue Statement?

The continue statement is a loop control statement that skips the remaining code in the current iteration and immediately moves to the next iteration of the loop. It's used when you want to exclude specific cases from processing without breaking out of the entire loop.

Key Characteristics:

  • Skips current iteration: Jumps to next cycle immediately
  • Works with all loops: for, while, do-while
  • Conditional skipping: Only skips when conditions are met
  • Doesn't terminate loop: Unlike break, the loop continues

Basic Continue Statement Syntax

for (int i = 0; i < n; i++) {
if (condition) {
continue;  // Skip rest of this iteration
}
// This code runs only if condition is false
}

Code Explanation with Examples

Example 1: Basic Continue in For Loop

public class BasicContinue {
public static void main(String[] args) {
// Skip even numbers
System.out.println("=== Skip Even Numbers ===");
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue;  // Skip even numbers
}
System.out.println("Odd number: " + i);
}
// Skip specific values
System.out.println("\n=== Skip Specific Numbers ===");
for (int i = 1; i <= 10; i++) {
if (i == 3 || i == 7) {
continue;  // Skip numbers 3 and 7
}
System.out.println("Number: " + i);
}
// Skip based on multiple conditions
System.out.println("\n=== Skip Multiples of 3 and 5 ===");
for (int i = 1; i <= 20; i++) {
if (i % 3 == 0 || i % 5 == 0) {
continue;  // Skip multiples of 3 or 5
}
System.out.println("Number: " + i);
}
}
}

Output:

=== Skip Even Numbers ===
Odd number: 1
Odd number: 3
Odd number: 5
Odd number: 7
Odd number: 9
=== Skip Specific Numbers ===
Number: 1
Number: 2
Number: 4
Number: 5
Number: 6
Number: 8
Number: 9
Number: 10
=== Skip Multiples of 3 and 5 ===
Number: 1
Number: 2
Number: 4
Number: 7
Number: 8
Number: 11
Number: 13
Number: 14
Number: 16
Number: 17
Number: 19

Example 2: Continue in While Loop

public class ContinueWhile {
public static void main(String[] args) {
// Skip negative numbers
System.out.println("=== Skip Negative Numbers ===");
int count = -5;
while (count <= 5) {
if (count < 0) {
count++;
continue;  // Skip negative numbers
}
System.out.println("Positive count: " + count);
count++;
}
// Process user input until specific value
System.out.println("\n=== Skip Invalid Input ===");
java.util.Scanner scanner = new java.util.Scanner(System.in);
int sum = 0;
int input;
System.out.println("Enter numbers (0 to stop, negative numbers will be skipped):");
while (true) {
input = scanner.nextInt();
if (input == 0) {
break;  // Exit loop
}
if (input < 0) {
System.out.println("Skipping negative number: " + input);
continue;  // Skip negative numbers
}
sum += input;
System.out.println("Added " + input + ", current sum: " + sum);
}
System.out.println("Final sum: " + sum);
scanner.close();
}
}

Output:

=== Skip Negative Numbers ===
Positive count: 0
Positive count: 1
Positive count: 2
Positive count: 3
Positive count: 4
Positive count: 5
=== Skip Invalid Input ===
Enter numbers (0 to stop, negative numbers will be skipped):
5
Added 5, current sum: 5
-3
Skipping negative number: -3
10
Added 10, current sum: 15
-1
Skipping negative number: -1
0
Final sum: 15

Example 3: Continue with Arrays and Collections

import java.util.*;
public class ContinueWithCollections {
public static void main(String[] args) {
// Array processing - skip empty strings
String[] words = {"Java", "", "Programming", "", "Language", " "};
System.out.println("=== Skip Empty Strings ===");
for (int i = 0; i < words.length; i++) {
if (words[i].trim().isEmpty()) {
continue;  // Skip empty or whitespace-only strings
}
System.out.println("Word: '" + words[i] + "'");
}
// ArrayList processing - skip null values
List<Integer> numbers = Arrays.asList(1, null, 3, null, 5, 6, null, 8);
System.out.println("\n=== Skip Null Values ===");
int sum = 0;
for (Integer num : numbers) {
if (num == null) {
continue;  // Skip null values
}
sum += num;
System.out.println("Added: " + num + ", Sum: " + sum);
}
System.out.println("Total sum: " + sum);
// String processing - skip vowels
String text = "Hello World";
System.out.println("\n=== Skip Vowels ===");
System.out.print("Consonants only: ");
for (char ch : text.toCharArray()) {
if ("AEIOUaeiou ".indexOf(ch) != -1) {
continue;  // Skip vowels and spaces
}
System.out.print(ch);
}
System.out.println();
// Array of objects - skip based on property
class Product {
String name;
double price;
boolean inStock;
Product(String name, double price, boolean inStock) {
this.name = name;
this.price = price;
this.inStock = inStock;
}
}
Product[] products = {
new Product("Laptop", 999.99, true),
new Product("Mouse", 29.99, false),
new Product("Keyboard", 79.99, true),
new Product("Monitor", 249.99, false)
};
System.out.println("\n=== In-Stock Products Only ===");
double total = 0;
for (Product product : products) {
if (!product.inStock) {
continue;  // Skip out-of-stock products
}
System.out.println(product.name + ": $" + product.price);
total += product.price;
}
System.out.println("Total for in-stock items: $" + total);
}
}

Output:

=== Skip Empty Strings ===
Word: 'Java'
Word: 'Programming'
Word: 'Language'
=== Skip Null Values ===
Added: 1, Sum: 1
Added: 3, Sum: 4
Added: 5, Sum: 9
Added: 6, Sum: 15
Added: 8, Sum: 23
Total sum: 23
=== Skip Vowels ===
Consonants only: HllWrld
=== In-Stock Products Only ===
Laptop: $999.99
Keyboard: $79.99
Total for in-stock items: $1079.98

Example 4: Continue in Nested Loops

public class ContinueNested {
public static void main(String[] args) {
// Skip specific combinations
System.out.println("=== Skip Diagonal Elements ===");
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
if (i == j) {
continue;  // Skip diagonal elements
}
System.out.print("(" + i + "," + j + ") ");
}
System.out.println();
}
// Skip rows with specific conditions
System.out.println("\n=== Skip Even Rows ===");
for (int row = 1; row <= 4; row++) {
if (row % 2 == 0) {
continue;  // Skip even-numbered rows
}
System.out.print("Row " + row + ": ");
for (int col = 1; col <= 3; col++) {
System.out.print(col + " ");
}
System.out.println();
}
// Complex condition with nested continue
System.out.println("\n=== Skip Specific Pairs ===");
for (int x = 1; x <= 3; x++) {
for (int y = 1; y <= 3; y++) {
if (x + y > 4) {
continue;  // Skip pairs where sum > 4
}
System.out.println("x=" + x + ", y=" + y + ", sum=" + (x + y));
}
}
// Matrix processing - skip zeros
int[][] matrix = {
{1, 0, 3},
{0, 5, 0},
{7, 0, 9}
};
System.out.println("\n=== Skip Zeros in Matrix ===");
int product = 1;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] == 0) {
continue;  // Skip zero values
}
System.out.println("Non-zero at [" + i + "][" + j + "]: " + matrix[i][j]);
product *= matrix[i][j];
}
}
System.out.println("Product of non-zero elements: " + product);
}
}

Output:

=== Skip Diagonal Elements ===
(1,2) (1,3) (1,4) (1,5) 
(2,1) (2,3) (2,4) (2,5) 
(3,1) (3,2) (3,4) (3,5) 
(4,1) (4,2) (4,3) (4,5) 
(5,1) (5,2) (5,3) (5,4) 
=== Skip Even Rows ===
Row 1: 1 2 3 
Row 3: 1 2 3 
=== Skip Specific Pairs ===
x=1, y=1, sum=2
x=1, y=2, sum=3
x=1, y=3, sum=4
x=2, y=1, sum=3
x=2, y=2, sum=4
x=3, y=1, sum=4
=== Skip Zeros in Matrix ===
Non-zero at [0][0]: 1
Non-zero at [0][2]: 3
Non-zero at [1][1]: 5
Non-zero at [2][0]: 7
Non-zero at [2][2]: 9
Product of non-zero elements: 945

Example 5: Real-World Practical Examples

import java.util.*;
public class RealWorldExamples {
public static void main(String[] args) {
// 1. Data Validation - Skip Invalid Records
System.out.println("=== DATA VALIDATION ===");
String[] userEmails = {
"[email protected]",
"invalid-email",
"[email protected]",
"not-an-email",
"[email protected]"
};
List<String> validEmails = new ArrayList<>();
for (String email : userEmails) {
if (!email.contains("@") || !email.contains(".")) {
System.out.println("Skipping invalid email: " + email);
continue;
}
validEmails.add(email);
System.out.println("Valid email: " + email);
}
System.out.println("Total valid emails: " + validEmails.size());
// 2. E-commerce - Skip Out-of-Stock Items
System.out.println("\n=== INVENTORY PROCESSING ===");
class CartItem {
String name;
double price;
int quantity;
boolean available;
CartItem(String name, double price, int quantity, boolean available) {
this.name = name;
this.price = price;
this.quantity = quantity;
this.available = available;
}
}
CartItem[] cart = {
new CartItem("Laptop", 999.99, 1, true),
new CartItem("Mouse", 29.99, 2, false),
new CartItem("Keyboard", 79.99, 1, true),
new CartItem("Monitor", 249.99, 1, false)
};
double cartTotal = 0;
for (CartItem item : cart) {
if (!item.available) {
System.out.println("Skipping out-of-stock: " + item.name);
continue;
}
double itemTotal = item.price * item.quantity;
cartTotal += itemTotal;
System.out.printf("%s: $%.2f x %d = $%.2f%n", 
item.name, item.price, item.quantity, itemTotal);
}
System.out.printf("Cart total (available items): $%.2f%n", cartTotal);
// 3. File Processing - Skip Header/Footer Lines
System.out.println("\n=== FILE PROCESSING ===");
String[] fileLines = {
"=== HEADER ===",
"Data Line 1: Important information",
"Data Line 2: More important data",
"Data Line 3: Critical numbers",
"=== FOOTER ===",
"Data Line 4: Should be processed",
"End of file"
};
System.out.println("Processing data lines:");
for (String line : fileLines) {
if (line.startsWith("===") || line.equals("End of file")) {
continue;  // Skip header, footer, and end marker
}
System.out.println("Processing: " + line);
}
// 4. Sensor Data - Skip Out-of-Range Values
System.out.println("\n=== SENSOR DATA FILTERING ===");
double[] sensorReadings = {25.5, 150.2, 30.1, -5.8, 45.3, 200.0, 28.7};
double minTemp = 0.0;
double maxTemp = 100.0;
double sum = 0;
int validReadings = 0;
for (double reading : sensorReadings) {
if (reading < minTemp || reading > maxTemp) {
System.out.printf("Skipping out-of-range reading: %.1f°C%n", reading);
continue;
}
sum += reading;
validReadings++;
System.out.printf("Valid reading: %.1f°C%n", reading);
}
if (validReadings > 0) {
double average = sum / validReadings;
System.out.printf("Average temperature: %.1f°C (%d valid readings)%n", 
average, validReadings);
}
}
}

Output:

=== DATA VALIDATION ===
Valid email: [email protected]
Skipping invalid email: invalid-email
Valid email: [email protected]
Skipping invalid email: not-an-email
Valid email: [email protected]
Total valid emails: 3
=== INVENTORY PROCESSING ===
Laptop: $999.99 x 1 = $999.99
Skipping out-of-stock: Mouse
Keyboard: $79.99 x 1 = $79.99
Skipping out-of-stock: Monitor
Cart total (available items): $1079.98
=== FILE PROCESSING ===
Processing data lines:
Processing: Data Line 1: Important information
Processing: Data Line 2: More important data
Processing: Data Line 3: Critical numbers
Processing: Data Line 4: Should be processed
=== SENSOR DATA FILTERING ===
Valid reading: 25.5°C
Skipping out-of-range reading: 150.2°C
Valid reading: 30.1°C
Skipping out-of-range reading: -5.8°C
Valid reading: 45.3°C
Skipping out-of-range reading: 200.0°C
Valid reading: 28.7°C
Average temperature: 32.3°C (4 valid readings)

Example 6: Continue with Labels

public class ContinueWithLabels {
public static void main(String[] args) {
// Continue with label - skip to next iteration of labeled loop
System.out.println("=== LABELED CONTINUE ===");
outerLoop:
for (int i = 1; i <= 3; i++) {
System.out.println("Outer loop i=" + i);
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
System.out.println("  Skipping to next outer iteration");
continue outerLoop;  // Skip to next i
}
System.out.println("  Inner loop j=" + j);
}
}
// Matrix processing with labeled continue
System.out.println("\n=== MATRIX PROCESSING ===");
int[][] data = {
{1, 2, 3},
{4, 0, 6},
{7, 8, 9}
};
rowLoop:
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
if (data[i][j] == 0) {
System.out.println("Skipping row " + i + " (contains zero)");
continue rowLoop;  // Skip entire row if zero found
}
}
// This only executes for rows without zeros
System.out.println("Processing row " + i + ": " + Arrays.toString(data[i]));
}
// Search with labeled continue
System.out.println("\n=== SEARCH WITH SKIP ===");
String[][] wordGrid = {
{"apple", "banana", "cherry"},
{"date", "ERROR", "fig"},
{"grape", "kiwi", "lemon"}
};
searchLoop:
for (int i = 0; i < wordGrid.length; i++) {
for (int j = 0; j < wordGrid[i].length; j++) {
if (wordGrid[i][j].equals("ERROR")) {
System.out.println("Found ERROR at [" + i + "][" + j + "] - skipping row");
continue searchLoop;  // Skip problematic row
}
System.out.println("Processing: " + wordGrid[i][j]);
}
}
}
}

Output:

=== LABELED CONTINUE ===
Outer loop i=1
Inner loop j=1
Inner loop j=2
Inner loop j=3
Outer loop i=2
Inner loop j=1
Skipping to next outer iteration
Outer loop i=3
Inner loop j=1
Inner loop j=2
Inner loop j=3
=== MATRIX PROCESSING ===
Processing row 0: [1, 2, 3]
Skipping row 1 (contains zero)
Processing row 2: [7, 8, 9]
=== SEARCH WITH SKIP ===
Processing: apple
Processing: banana
Processing: cherry
Found ERROR at [1][1] - skipping row
Processing: grape
Processing: kiwi
Processing: lemon

Example 7: Common Pitfalls and Best Practices

public class PitfallsAndBestPractices {
public static void main(String[] args) {
// ❌ COMMON PITFALLS
// 1. Unreachable code after continue
System.out.println("=== UNREACHABLE CODE ===");
for (int i = 1; i <= 3; i++) {
if (i == 2) {
continue;
// System.out.println("This never executes!"); // ❌ Compilation error
}
System.out.println("i = " + i);
}
// 2. Continue in wrong place (infinite loop risk)
System.out.println("\n=== INFINITE LOOP RISK ===");
int count = 0;
while (count < 5) {
count++;
if (count == 3) {
continue;  // This is OK because count was incremented first
}
System.out.println("Count: " + count);
}
// ❌ Dangerous version:
/*
count = 0;
while (count < 5) {
if (count == 3) {
continue;  // ❌ count never increments, infinite loop!
}
System.out.println("Count: " + count);
count++;
}
*/
// ✅ BEST PRACTICES
// 1. Use clear condition names
System.out.println("\n=== CLEAR CONDITIONS ===");
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (int num : numbers) {
boolean isEven = (num % 2 == 0);
boolean isMultipleOfThree = (num % 3 == 0);
if (isEven && isMultipleOfThree) {
continue;  // Skip numbers divisible by 6
}
System.out.println("Processing: " + num);
}
// 2. Extract complex skip logic to methods
System.out.println("\n=== EXTRACTED LOGIC ===");
String[] usernames = {"john_doe", "admin", "user123", "test", "guest"};
for (String username : usernames) {
if (shouldSkipUsername(username)) {
System.out.println("Skipping username: " + username);
continue;
}
System.out.println("Processing user: " + username);
}
// 3. Use continue for early validation
System.out.println("\n=== EARLY VALIDATION ===");
String[] inputs = {"123", "abc", "45.6", "789", "xyz"};
for (String input : inputs) {
// Early validation - skip non-numeric inputs
if (!isNumeric(input)) {
System.out.println("Skipping non-numeric: " + input);
continue;
}
// Process only valid numeric inputs
int number = Integer.parseInt(input);
System.out.println("Valid number: " + number + ", Square: " + (number * number));
}
}
// Helper method for complex skip logic
public static boolean shouldSkipUsername(String username) {
return username.equals("admin") || 
username.equals("test") || 
username.equals("guest") ||
username.length() < 4;
}
// Helper method for validation
public static boolean isNumeric(String str) {
try {
Integer.parseInt(str);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}

Output:

=== UNREACHABLE CODE ===
i = 1
i = 3
=== INFINITE LOOP RISK ===
Count: 1
Count: 2
Count: 4
Count: 5
=== CLEAR CONDITIONS ===
Processing: 1
Processing: 2
Processing: 3
Processing: 4
Processing: 5
Processing: 7
Processing: 8
Processing: 9
Processing: 10
=== EXTRACTED LOGIC ===
Skipping username: admin
Processing user: john_doe
Skipping username: user123
Skipping username: test
Skipping username: guest
=== EARLY VALIDATION ===
Valid number: 123, Square: 15129
Skipping non-numeric: abc
Skipping non-numeric: 45.6
Valid number: 789, Square: 622521
Skipping non-numeric: xyz

Continue vs Break Comparison

AspectContinueBreak
EffectSkips current iterationExits entire loop
Loop Continues?YesNo
Use CaseSkip specific casesStop when condition met
Nested LoopsAffects current loop onlyCan use labels for outer loops

Best Practices

  1. Use for filtering: Perfect for skipping invalid or unwanted data
  2. Early validation: Put continue conditions at the start of loops
  3. Clear conditions: Use descriptive boolean variables for complex conditions
  4. Avoid deep nesting: Extract complex skip logic to helper methods
  5. Watch for infinite loops: Ensure loop variables update before continue
  6. Use labeled continue sparingly: Can make code harder to understand

When to Use Continue

✅ Good Use Cases:

  • Data filtering: Skip invalid, corrupted, or unwanted data
  • Input validation: Skip processing invalid user input
  • Resource handling: Skip unavailable or busy resources
  • Conditional processing: Skip elements that don't meet criteria
  • Error handling: Skip problematic records and continue processing others

❌ Avoid When:

  • The condition is too complex (extract to method)
  • It makes the loop logic hard to understand
  • You're using it as a substitute for proper error handling
  • It creates deeply nested conditional logic

Conclusion

The continue statement is like a selective filter for your loops:

  • Skips unwanted iterations: Filters out specific cases
  • Maintains loop flow: Continues with next iteration
  • Perfect for validation: Early exit from invalid cases
  • Works with all loops: for, while, do-while
  • Labeled version: Can skip outer loop iterations

Key Takeaways:

  • Use continue for filtering - skip specific elements while processing others
  • Place continue early in the loop body for efficiency
  • Extract complex conditions to helper methods for readability
  • Watch for infinite loops when using continue with while loops
  • Use labeled continue sparingly - it can make code harder to follow

The continue statement is your best friend when you need to process most elements in a collection but skip a few specific cases. It's the perfect tool for clean, efficient data filtering and validation!

Leave a Reply

Your email address will not be published. Required fields are marked *


Macro Nepal Helper