Break Statement in Java

Break Statement in Java

Break statement is used to exit the loop.we can use break statement in for,do ,while , switch and may other looping statements .when the controller encounters break; ,the controller skips the further code and goes to next statement outside the loop.

syntax:

break;

flowchart:

Flow Chart of Break Statement in Java

Working of break statement:

Working of break statement in Java

example

import java.util.*;
class X2
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
int i=0,x=0,sum=0;
for (i=1;i<=5;i++)
{
System.out.printf("enter %dst number ",i);
x=s.nextInt();
if(x<0 || x==0)
{
break;
}
sum += x;
}
System.out.printf("the total sum is %d",sum);
s.close();
}
}

Output

enter 1st number 10
enter 2st number 20
enter 3st number 30
enter 4st number 0
the total sum is 60

this example is for the addition of any five numbers. but if the user gives any negative number the loop will be stopped using the break statement.

Last updated on by vishal devxo