Search code examples
javacontinue

Continue statement in Java


I adding a continue statement to end the current iteration so that the rest of the statement in the loop body is not executed.

public class Main {
    public static void main(String[] args) {
        int sum = 0;
        int number = 0;
        while (number < 20) {
            number++;
            if (number == 10 || number == 11)
                continue;
            sum += number;
        }
        System.out.println(sum);
    }
}

The things I can't understand is why I will get error if I added {} ?

public class Main {
    public static void main(String[] args) {
        int sum = 0;
        int number = 0;
        while (number < 20) {
            number++;
            if (number == 10 || number == 11) {
                continue;
                sum += number;
            }
        }
        System.out.println(sum);
    }
}

Error

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    Unreachable code

    at Main.main(Main.java:18)

Solution

  • This will work.

    if (number == 10 || number == 11) {
        continue;
    }
    sum += number;
    

    Explanation

    When you don't add {} to your if statement, only the next line will be considered. Therefore, you need to leave sum += number outside the {}