In this tutorial, you will learn about the break statement, how to use break statement with for-loop,while-loop,do-while loop,switch statement in Java with the help of examples.
The break statement in Java programming language has the following two usages −
When the break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop.
It can be used to terminate a case in the switch statement.
break;
//Java Program to demonstrate the use of break statement
//inside the for loop.
public class BreakExample
{
public static void main(String[] args)
{
//using for loop
for(int i=1;i<=10;i++)
{
if(i==5)
{
//breaking the loop
break;
}
System.out.println(i);
}
}
}
Output :
1
2
3
4
//Java Program to demonstrate the use of break statement
//inside the while loop.
public class BreakWhileExample
{
public static void main(String[] args)
{
//while loop
int i=1;
while(i<=10)
{
if(i==5)
{
//using break statement
i++;
break; //it will break the loop
}
System.out.println(i);
i++;
}
}
}
Output :
1
2
3
4
//Java Program to demonstrate the use of break statement
//inside the Java do-while loop.
public class BreakDoWhileExample
{
public static void main(String[] args)
{
//declaring variable
int i=1;
//do-while loop
do
{
if(i==5)
{
//using break statement
i++;
break; //it will break the loop
}
System.out.println(i);
i++;
}
while(i<=10);
}
}
Output :
1
2
3
4
//Java Program to demonstrate the use of break statement
//inside the Java switch statement.
public class SwitchExample
{
public static void main(String[] args)
{
//Declaring a variable for switch expression
int number=20;
//Switch expression
switch(number)
{
//Case statements
case 10: System.out.println("10");
break;
case 20: System.out.println("20");
break;
case 30: System.out.println("30");
break;
//Default case statement
default : System.out.println("Not in 10, 20 or 30");
}
}
}
Output :
20