Break statement in java with example

Break statement is used to exit from loop

Break statement in loops

Break statement immediately transfer control to the out of loop and statement which is immediately after loop is executed. In other word break statement terminate loop.

Note:-
# Break is terminated only one loop in case of nested loop

Example:-

Java program to count N number using break statement

import java.util.Scanner;

class group{
public static void main(String angt[]){
Scanner data = new Scanner(System.in);
int num,i;
System.out.println("Enter a number below 100");
num=data.nextInt();
for(i=1;i<100;i++)
{
System.out.println(i);
if(i==num)
break;
}
}
}
Example:-

Break statement in nested loop

import java.util.Scanner;

class group{
public static void main(String angt[]){
Scanner data = new Scanner(System.in);
int num,i,j;
System.out.println("Enter a number below 100");
num=data.nextInt();
for(j=0;j<2;j++)
{
for(i=1;i<100;i++)
{
System.out.println(i);
if(i==num)
break;
}
System.out.println("\t");
}
}
}

Break statement in switch

The break statement transfer the control to out of the switch statement and statement which is immediately after switch is executed.

Note:-
# break is optional, if 2 or more case labels belongs to same statement.

Program to accept day number of week and display the corresponding week day

import java.util.Scanner;
class group{
public static void main(String arg[]){
int day;
Scanner week = new Scanner(System.in);
System.out.println("Enter day number of the week ");
day = week.nextInt();
switch(day){
case 1:
System.out.println("Sunday");
break;
case 2:
System.out.println("Monday");
break;
case 3:
System.out.println("Tuesday");
break;
case 4:
System.out.println("Wednesday");
break;
case 5:
System.out.println("Thursday");
break;
case 6:
System.out.println("Friday");
break;
case 7:
System.out.println("Saturday");
break;
}
}
}


Previous Code:-
Trigonometric function in java

List Code:-
Java codes

Next Code:-
Continue statement in java

Java Programs:-
List of Java Programs

Leave reply

Add your comments here

Back to Top