Break Keyword in Java With Example | What is Uses of Break Statement?

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 –

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

Leave a Comment