Branching Statements in Java Control Statements
Java provides the break, continue, and return statements for transferring program control. These statements change the order in which a program is executed.
break Statement
The break statement has three roles.
- It is used to exit a
switchstatement. - It is used to exit a loop.
- It is used as an improved form of the
gotostatement used in older programs.
continue Statement
When a continue statement is encountered inside a loop, execution stops and control moves to the beginning of the loop.
The following example uses the continue statement to calculate the sum of odd numbers from 1 to 100.
package com.devkuma.tutorial.control.statement;
public class Continue {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 100; i++) {
if (i % 2 == 0) {
continue;
}
sum += i;
}
System.out.println("sum=" + sum);
}
}
return Statement
The return statement stops the currently executing method and returns control to the place that called the current method.
The following example receives a number in a method and checks whether it is a multiple of 3.
package com.devkuma.tutorial.control.statement;
public class Return {
public void check(int i) {
if (i % 3 == 0) {
System.out.println(i + "는 3의 배수이다.");
return;
}
System.out.println(i + "는 3의 배수가 아니다.");
}
public static void main(String[] args) {
Return r = new Return();
r.check(6);
}
}