Java Break Statement

Java Break Statement

When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop.

The Java break statement is used to break loop or switch statement. It breaks the current flow of the program at specified condition. In case of inner loop, it breaks only inner loop.

We can use Java break statement in all types of loops such as for loop, while loop and do-while loop.

Syntax:

Flowchart of Break Statement

java break statement flowchart

Java Break Statement with Loop

Example:

BreakExample.java

Output:

1
2
3
4

Java Break Statement with Inner Loop

It breaks inner loop only if you use break statement inside the inner loop.

Example:

BreakExample2.java

Output:

1 1
1 2
1 3
2 1
3 1
3 2
3 3

Java Break Statement with Labeled For Loop

We can use break statement with a label. The feature is introduced since JDK 1.5. So, we can break any loop in Java now whether it is outer or inner loop.

Example:

BreakExample3.java

Output:

1 1
1 2
1 3
2 1

Java Break Statement in while loop

Example:

BreakWhileExample.java

Output:

1
2
3
4

Java Break Statement in do-while loop

Example:

BreakDoWhileExample.java

Output:

1
2
3
4

Java Break Statement with Switch

To understand the example of break with switch statement, please visit here: Java Switch Statement.


原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/java/263847.html

(0)
上一篇 2022年6月1日 15:36
下一篇 2022年6月1日 15:36

相关推荐

发表回复

登录后才能评论