Continue Keyword in Java for loop Best Example

Continue Keyword in Java : –The continue keyword in Java is used to skip the current iteration of a loop and move to the next iteration. It can be especially useful in situations where you want to skip certain iterations of a loop based on a condition.

Table of Contents

Here’s an example of how you might use the continue keyword in a for loop in Java:

public class A {
	public static void main( String[] args) {
		for (int i=0; i<5; i++) {
			if(i==2){
			
			continue;
		}
		
		System.out.println(i);
		}
	}
}
Output : 
0
1
3
4

How to Stop infinite for loop in java

public class A {
	public static void main( String[] args) {
		int x=0;
		for (; ;) {
			
			if(x==5) {
				break;
			}
			x++;
			System.out.println(x);
		}
		
	}
}
Output : 
1
2
3
4
5

Continue Keyword in Java

for (int i = 0; i < 10; i++) {
    if (i == 5) {
        continue; // skip iteration if i is 5
    }
    System.out.println(i);
}

In this example, the for loop runs 10 times, from i=0 to i=9. However, when i=5, the continue keyword is executed, which skips the rest of the current iteration and moves on to the next iteration. As a result, the number 5 is not printed to the console.

Here’s another example that demonstrates how you might use continue to skip even numbers in a loop:

for (int i = 0; i < 10; i++) {
    if (i % 2 == 0) {
        continue; // skip even numbers
    }
    System.out.println(i);
}

In this example, the for loop runs 10 times, from i=0 to i=9. However, when i is an even number (i.e., i % 2 == 0), the continue keyword is executed, which skips the rest of the current iteration and moves on to the next iteration. As a result, only the odd numbers (1, 3, 5, 7, and 9) are printed to the console.

Leave a Comment