Break Keyword in Java : –
- It Should be Used Only inside Loops or Switch.
- It Will Exit Loop.
Break Keyword in Java With Example
public class A {
public static void main(String[] args) {
for(int i=0; i<5; i++) {
break;
System.out.println(100); // Unreachable Code Error
}
}
}
Example 2 : Use Break Keyword in Java for loop
public class A {
public static void main(String[] args) {
for(int i=0; i<5; i++) {
System.out.println(100);
break;
}
}
}
Output : 100
You Also Learn –
- What is inheritance in Java
- What is Abstract Class in Java
- What is Lambda Expression in Java 8
- Types of Exception in Java
- What is Final Keyword in Java
- What is Exception Handling in Java
- What is Interface in Java
- What is Wrapper Class in Java
Use If Statement in Java for loop
public class A {
public static void main(String[] args) {
for(int i=0; i<5; i++) {
if (i==4) {
break;
}
System.out.println(i);
}
}
}
Output :
0
1
2
3
Use of for loop in java
public class A {
public static void main(String[] args) {
for(int i=0; i<5; i++) {
System.out.println("Hello");
}
}
}
Output :
Hello
Hello
Hello
Hello
Hello
Labeled Break Keyword in Java for loop Example
Example 1
public class A {
public static void main(String[] args) {
for (int i=0; i<5; i++) {
x: if (i==2) {
break x;
}
System.out.println(i);
}
}
}
Output :
0
1
2
3
4
Example 2
public class A {
public static void main(String[] args) {
x:for (int i=0; i<5; i++) {
if (i==2) {
break x;
}
System.out.println(i);
}
}
}
Output :
0
1