break & Continue

In Java, break is used to terminate a loop immediately, while continue skips the current iteration and jumps to the next one

 

Key Differences

 

Break vs Continue: break kills the loop entirely; continue just skips the current "lap".

 

 

package loopsbreakcontinuedemo1;

 

public class LoopsbreakContinueDemo1

{

    public static void main(String[] args)

    {

        // 1. FOR LOOP: Used when the number of iterations is known

        System.out.println("--- For Loop (Skip 3, Stop at 7) ---");

        for (int i = 1; i <= 10; i++)

        {

            if (i == 3)

            {

                continue; // Skip number 3

            }

            if (i == 7)

            {

                break;    // Stop the loop at 7

            }

            System.out.print(i + " ");

        }

 

        // 2. WHILE LOOP: Checks condition before execution

        System.out.println("\n\n--- While Loop (Skip Evens, Stop at 9) ---");

        int j = 0;

        while (j < 10)

        {

            j++;

            if (j % 2 == 0)

            {

                continue; // Skip even numbers

            }

            if (j > 8)

            {

                break;         // Exit if greater than 8

            }

            System.out.print(j + " ");

        }

 

        // 3. DO-WHILE LOOP: Executes at least once before checking condition

        System.out.println("\n\n--- Do-While Loop (Skip 2, Stop at 5) ---");

        int k = 1;

        do

        {

            if (k == 2)

            {

                k++;

                continue; // Skip rest of body and check condition

            }

            if (k == 5)

            {

                break; // Exit loop

            }

            System.out.print(k + " ");

            k++;

        } while (k <= 10);

    }

}