⬅ Previous Topic
Java const KeywordNext Topic ⮕
Java default Keyword⬅ Previous Topic
Java const KeywordNext Topic ⮕
Java default Keywordcontinue
Keyword in JavaThe continue
keyword in Java is used to skip the current iteration of a loop and jump to the next one. It gives you finer control over the flow of loops, especially when certain conditions should interrupt the current cycle without exiting the loop entirely.
continue
?Imagine you’re looping over a list of numbers, but want to skip processing any negative values. Or perhaps you're filtering strings and want to avoid ones that are empty. The continue
keyword makes your code cleaner and avoids deeply nested if-statements.
continue;
That’s it. The keyword stands alone and ends with a semicolon. It’s typically placed inside an if
condition inside loops.
continue
Works in a LoopWhen the Java runtime encounters continue
, it immediately skips to the next iteration of the nearest enclosing loop. Any code written after continue;
in the current iteration is not executed.
for
Looppublic class ContinueExample1 {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
System.out.println("Odd number: " + i);
}
}
}
Odd number: 1
Odd number: 3
Odd number: 5
Odd number: 7
Odd number: 9
Whenever i % 2 == 0
evaluates to true (i.e., the number is even), the continue
statement is triggered. This skips the System.out.println()
call and moves on to the next iteration.
continue
in a while
Looppublic class ContinueExample2 {
public static void main(String[] args) {
int i = 0;
while (i < 10) {
i++;
if (i == 5) {
continue; // Skip when i is 5
}
System.out.println("Value: " + i);
}
}
}
Value: 1
Value: 2
Value: 3
Value: 4
Value: 6
Value: 7
Value: 8
Value: 9
Value: 10
When i
becomes 5, continue
is executed. The System.out.println()
line is skipped for that specific iteration.
continue
with a for-each
Looppublic class ContinueExample3 {
public static void main(String[] args) {
String[] fruits = {"Apple", "", "Banana", "Mango", ""};
for (String fruit : fruits) {
if (fruit.isEmpty()) {
continue; // Skip empty strings
}
System.out.println("Fruit: " + fruit);
}
}
}
Fruit: Apple
Fruit: Banana
Fruit: Mango
We use continue
to skip printing any empty strings. This pattern is useful in data cleansing or filtering scenarios.
continue
while
or do-while
loops, continue
can cause the loop condition never to be updated. Always ensure variables are updated before the continue
.continue
statement inside a block will make that code unreachable for that execution path.continue
— Best PracticesThe continue
keyword is ideal when:
⬅ Previous Topic
Java const KeywordNext Topic ⮕
Java default KeywordYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.