Java - Use of Break and Continue statements
break statement is used to come out the loop.
continue statement is used to continue the loop but skip the execution of the remaining statements in the loop.
These statements are used in any loop statements (for,do while, while) and switch case statements.
The sample code given below has infinite for loop. if i >= 60, then break statement will get executed and loop will get terminated. if (i % 2) is false meaning odd number, then the continue statement will skip the remainder of the statement. In this case, event count will not get incremented.
Source Code
import java.lang.*;
import java.util.*;
import java.io.*;
class BreakContinue
{
public static void main(String[] args)
{
int evencount = 0, i = 0;
for(i = 0; ; i++)
{
if(i >= 60)
break; // Terminate the for loop
if((i % 2) != 0)
continue; // Will skip the reminder of the for loop
evencount++;
}
System.out.format("Total Even Numbers Between 0 to 60 is: %d", evencount);
}
}
Output
Total Even Numbers Between 0 – 60 is: 31
|