Break and Continue statements.
Break statement
The Break statement is used to exit from the loop for a particular condition.
Sometimes it is necessary to stop the execution of program at certain condition.
Uses of break statement
- It is used in switch case statement to break when matching case is found.
- It is also used in the looping such as while,do-while and for loop etc.
- It is used in looping to immediately exit or terminate the loop.
Flowchart
Syntax
break;
Example - break using switch case
Program to stop the case execution when break statement is found.
public class BreakSwitch
{
public static void main(String[] args)
{
int num = 1;
switch(num)
{
case 1:
System.out.println("I'm case 1");
case 2:
System.out.println("I'm case 2");
case 3:
System.out.println("I'm case 3");
break;
case 4:
System.out.println("I'm case 4");
}
}
}
Output
I'm case 1
I'm case 2
I'm case 3
Example - break using loop
Program to stop the loop execution when break statement is found.
public class BreakLoop
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
if(i==5)
break;
else
System.out.println("i = "+i);
}
}
}
Output
i = 1
i = 2
i = 3
i = 4
NOTE : All the statements written after the break statement inside the loop becomes unreachable for code. For better practive we must use break statement at the end of loop. |
Continue statement
The continue statement is used to skip the current iteration of loop and goto next iteration without stopping the loop.
Flowchart
Syntax
continue;
Example
public class ContinueTest
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
if(i==5)
continue;
else
System.out.println("i = "+i);
}
}
}
Output
i = 1
i = 2
i = 3
i = 4
i = 6
i = 7
i = 8
i = 9
i = 10
Difference between Break and Continue statement
Sr.No |
Break statement |
Continue statement |
1. |
It can be used in switch and loops |
It is used in loops only. |
2. |
It terminates the execution process for given condition |
It does not terminate the execution process but it skips the statements when given condition becomes true. |
3. |
when break appears, the control goes out of the switch of loop |
when continue appears, the control goes at the beginning of the loop. |