Monday, April 28, 2025

Java Tutorial - Break and Continue inside For Loop

In programming, "break" and "continue" are control flow statements that allow you to modify the behavior of loops.

  • "break" is a keyword used to exit from a loop prematurely. When a "break" statement is encountered within a loop, the loop immediately terminates, and the program execution continues with the first statement after the loop.
  • "continue" is a keyword used to skip the current iteration of a loop and continue with the next iteration. When a "continue" statement is encountered within a loop, the remaining statements in the loop are skipped, and the program execution continues with the next iteration of the loop.

 Break Example

public class Main {

	public static void main(String[] args) {
		
		for (int x = 0; x < 10; x++) {
			if (x == 3) {				
				break;
			}			
			System.out.println(x);
		}			 
	}	
}

This Java code defines a class called "Main" that contains a main method. The main method initializes a for loop that iterates over the values of the integer variable "x" from 0 to 9.

Inside the for loop, there is an if statement that checks if the value of "x" is equal to 3. If this condition is true, the "break" keyword is executed, which immediately terminates the loop and proceeds to the first statement after the loop.

If the condition in the if statement is false, the print statement within the for loop is executed, which prints the value of "x" to the console.

The output of this code, as written, would be: 

0
1
2

Continue Example

Notice that the loop terminates when "x" is equal to 3, and the value 3 is not printed to the console.

public class Main {

	public static void main(String[] args) {
		
		for (int x = 0; x < 10; x++) {
			if (x == 3) {
				continue;
				//break;
			}			
			System.out.println(x);
		}			 
	}	
}

Inside the for loop, there is an if statement that checks if the value of "x" is equal to 3. If this condition is true, the "continue" keyword is executed, which skips the remaining statements in the loop and immediately proceeds to the next iteration. If the "break" keyword were used instead of "continue", the loop would terminate prematurely when "x" is equal to 3.

If the condition in the if statement is false, the print statement within the for loop is executed, which prints the value of "x" to the console.

The output of this code, as written, would be: 

0
1
2
4
5
6
7
8
9

Notice that the value 3 is skipped due to the "continue" statement within the loop.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...