Sometimes when we apply loops we need to come out of the loop on occurrence of particular condition. This can be achieved by break statement. Following program illustrates the use of break in the for loop.
The break and continue Statement
Sometimes
when we apply loops we need to come out of the loop on occurrence of particular
condition. This can be achieved by break statement. Following program
illustrates the use of break in the for loop.
Java
Program [breakdemo.java]
1*
This
program shows the use of break statement
*/
class
breakdemo
{
public
static void main(String args[])
{
for(int
i=1;i<=20;i++)
{
if(i%10==0)
{
System.out.println("number
"+i+" is divisible by 10");
break;//come
out of for loop
}
else
System.out.println("number
"+i+" is not divisible by 10");
}
}
}
Output
The
number 1 is not divisible by 10
The
number 2 is not divisible by 10
The
number 3 is not divisible by 10
The
number 4 is not divisible by 10
The
number 5 is not divisible by 10
The
number 6 is not divisible by 10
The
number 7 is not divisible by 10
The
number 8 is not divisible by 10
The
number 9 is not divisible by 10
The
number 10 is divisible by 10
Program explanation: Note
that in the above program the numbers after 10 will not be considered at all.
This is because when we reach at 10 then if condition becomes true and we
encounter break statement. This forces us to come out of for loop. Just look at
the output of corresponding program!!!
Similarly
we can use the return statement which is useful for returning the control from
the current block.
Object Oriented Programming: Unit I: Introduction to OOP and Java : Tag: : with Example Java Programs - The Break and Continue Statements
Object Oriented Programming
CS3391 3rd Semester CSE Dept | 2021 Regulation | 3rd Semester CSE Dept 2021 Regulation