Java Continue

Su Suriya Ravichandran Updated 14 Nov 2026
4 min read ·Lesson 22 of 306

The continue statement skips the rest of the current loop iteration and moves straight to the next one. Unlike break, the loop does not end; only the remaining statements in this pass are skipped. It is used to filter out items that should not be processed, without wrapping the main logic in a large if block.

continue in a for Loop

for (int i = 1; i <= 6; i++) {
    if (i % 2 == 0) {
        continue;
    }
    System.out.println(i);
}

Output:

1
3
5

When i is even, continue skips the println. In a for loop, control then goes to the update (i++) and then to the condition, exactly as if the body had finished normally. The loop runs all six iterations; only the even ones produce no output.

continue in while and do-while

In a while or do-while loop, continue jumps directly to the condition. Any update that sits at the bottom of the body is skipped too, which can create an infinite loop:

int i = 0;
while (i < 6) {
    if (i % 2 == 0) {
        continue;      // i++ below is never reached when i is even
    }
    System.out.println(i);
    i++;
}
// i stays 0 forever

The fix is to update the loop variable before any continue can run:

int i = 0;
while (i < 6) {
    i++;
    if (i % 2 == 0) {
        continue;
    }
    System.out.println(i);
}

Output:

1
3
5

This difference is one reason for loops are safer for counting: the update lives in the header and runs even after continue.

LoopWhere continue jumps
forTo the update, then the condition
Enhanced forTo the next element
whileTo the condition
do-whileTo the condition at the bottom

Skipping Invalid Data

continue is most useful as an early filter at the top of a loop body. Each unwanted case is rejected in one line, and the main processing stays unindented:

String[] lines = {"42", "", "17", "# comment", "abc", "8"};
int sum = 0;

for (String line : lines) {
    line = line.strip();
    if (line.isEmpty()) {
        continue;                 // skip blank lines
    }
    if (line.startsWith("#")) {
        continue;                 // skip comments
    }
    try {
        sum += Integer.parseInt(line);
    } catch (NumberFormatException e) {
        System.out.println("Skipping invalid value: " + line);
    }
}
System.out.println("Sum: " + sum);

Output:

Skipping invalid value: abc
Sum: 67

Compare the same logic without continue:

for (String line : lines) {
    line = line.strip();
    if (!line.isEmpty()) {
        if (!line.startsWith("#")) {
            // main logic, indented two levels deeper
        }
    }
}

Both work. With several filters, the continue version stays flat and lists each rejection rule separately, which reads more like the rules themselves.

continue Versus break

int[] values = {3, -1, 7, -4, 5};

System.out.print("continue: ");
for (int v : values) {
    if (v < 0) continue;
    System.out.print(v + " ");
}
System.out.println();

System.out.print("break:    ");
for (int v : values) {
    if (v < 0) break;
    System.out.print(v + " ");
}
System.out.println();

Output:

continue: 3 7 5
break:    3

continue skips the negative numbers and keeps going. break stops at the first negative number and ignores everything after it.

Labeled continue

In nested loops, a plain continue affects only the innermost loop. A labeled continue skips to the next iteration of an outer loop:

String[] words = {"apple", "sky", "rhythm", "tree"};

outer:
for (String word : words) {
    for (char c : word.toCharArray()) {
        if ("aeiou".indexOf(c) >= 0) {
            System.out.println(word + " has a vowel");
            continue outer;
        }
    }
    System.out.println(word + " has no vowels");
}

Output:

apple has a vowel
sky has no vowels
rhythm has no vowels
tree has a vowel

As soon as a vowel is found, continue outer abandons the inner character loop and skips the "no vowels" line, moving straight to the next word. With a plain continue, the inner loop would just move to the next character. The "no vowels" message runs only when the inner loop finishes without finding one.

As with labeled break, moving the inner loop into a helper method (boolean hasVowel(String word)) often makes the code clearer than a label.

Practical Example: Processing Orders

import java.util.List;

public class OrderProcessor {
    record Order(String id, String status, double amount, String country) {}

    public static void main(String[] args) {
        List<Order> orders = List.of(
            new Order("A1", "PAID", 1200, "IN"),
            new Order("A2", "CANCELLED", 800, "IN"),
            new Order("A3", "PAID", 0, "IN"),
            new Order("A4", "PAID", 450, "US"),
            new Order("A5", "PAID", 3000, "IN")
        );

        double revenue = 0;
        int processed = 0;

        for (Order o : orders) {
            if (!o.status().equals("PAID")) {
                continue;                          // only paid orders
            }
            if (o.amount() <= 0) {
                System.out.println("Warning: " + o.id() + " has no amount");
                continue;                          // data problem; skip
            }
            if (!o.country().equals("IN")) {
                continue;                          // domestic report only
            }

            revenue += o.amount();
            processed++;
            System.out.println("Processed " + o.id());
        }

        System.out.printf("%d orders, revenue %.2f%n", processed, revenue);
    }
}

Output:

Processed A1
Warning: A3 has no amount
Processed A5
2 orders, revenue 4200.00

Each continue expresses one business rule. Orders that are not paid, have no amount, or are international are skipped, and the main processing at the bottom runs only for orders that pass every rule. A new rule can be added as another two-line guard without restructuring the loop. The record declares a compact data class; records have their own lesson in the OOP section.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Continue and get answers drawn from it.

Signed-in readers only.