The break statement in Java immediately ends the loop, and the program's control shifts to the statement that follows the loop.
Flow Chart
As a loop control statement, the break statement is used to end the loop. The loop iterations end as soon as the break statement is encountered from within the loop, and control is immediately transferred from the loop to the first statement following the loop.
Break statements are generally used when we are unsure of the precise number of loop iterations or when we want to end the loop based on a condition.
Syntax
break;
// Java Loop program using do.. while loop
public class Student { public static void main(String[] args) { for(int i = 1; i<=5; i++) { System.out.println(i); if(i==3) { break; // loop will stop here } } } }
Output:
1
2
3
// break statement with labeled for loop
public class LabeledForExample { public static void main(String[] args) { xyz: //Using Label for outer and for loop for(int a = 1; a <= 3; a++) { abc: for(int b = 1; b <= 3; b++) { if(a==2 && b==2) { break xyz; } System.out.println(a+" "+b); } } } }
Output:
1 1
1 2
1 3
2 1
// break statement with while loop
public class LabeledForExample{ public static void main(String[] args){ int i=1; while(i<=5){ if(i==4){ i++; break; } System.out.println(i); i++; } } }
Output:
1
2
3
// break statement with do.. while loop
public class Student{ public static void main(String[] args){ int i=1; do { if(i==4){ i++; break; } System.out.println(i); i++; } while (i<=5); } }
Output:
1
2
3
Police Colony
Patna, Bihar
India
Email:
Post your comment