Java Control Flow Statements : Page 3 of 3

Control statements control the order of execution in a java program, based on data values and conditional logic. There are three main categories of control flow statements;

Selection statements: if, if-else and switch.

Loop statements: while, do-while and for.

Transfer statements: break, continue, return, try-catch-finally and assert.

We use control statements when we want to change the default sequential order of execution

 

TRANSFER STATEMENTS

 

Continue Statement

A continue statement stops the iteration of a loop (while, do or for) and causes execution to resume at the top of the nearest enclosing loop. You use a continue statement when you do not want to execute the remaining statements in the loop, but you do not want to exit the loop itself.

The syntax of the continue statement is

continue; // the unlabeled form
continue <label>; // the labeled form

You can also provide a loop with a label and then use the label in your continue statement. The label name is optional, and is usually only used when you wish to return to the outermost loop in a series of nested loops.

Below is a program to demonstrate the use of continue statement to print Odd Numbers between 1 to 10.

public class ContinueExample {

	public static void main(String[] args) {
		System.out.println("Odd Numbers");
		for (int i = 1; i <= 10; ++i) {
			if (i % 2 == 0)
				continue;
			// Rest of loop body skipped when i is even
			System.out.println(i + "\t");
		}
	}
}

Output

Odd Numbers
1
3
5
7
9

Download ContinueExample.java

 

Break Statement

The break statement transfers control out of the enclosing loop ( for, while, do or switch statement). You use a break statement when you want to jump immediately to the statement following the enclosing control structure. You can also provide a loop with a label, and then use the label in your break statement. The label name is optional, and is usually only used when you wish to terminate the outermost loop in a series of nested loops.

The Syntax for break statement is as shown below;

break; // the unlabeled form
break <label>; // the labeled form

Below is a program to demonstrate the use of break statement to print numbers Numbers 1 to 10.

public class BreakExample {

	public static void main(String[] args) {
		System.out.println("Numbers 1 - 10");
		for (int i = 1;; ++i) {
			if (i == 11)
				break;
			// Rest of loop body skipped when i is even
			System.out.println(i + "\t");
		}
	}
}

Output

Numbers 1 – 10
1
2
3
4
5
6
7
8
9
10

Download BreakExample.java

 

Like us on Facebook