- Java Programming Basics
- Java Tutorial
- Java Overview
- Java Environment Setup
- Java Program Structure
- Java Basic Syntax
- Java First Program
- Java Constants
- Java Separators
- Java Keywords
- Java Data Types
- Java Data Types
- Java Integers
- Java Floating Point
- Java Characters
- Java Booleans
- Java Numbers
- Java Programming Variables
- Java Variables
- Java Variable Types
- Java Variable Scope
- Java Type Conversion
- Java Type Casting
- Java Auto Type Promotion
- Java Type Promotion Rules
- Java Programming Arrays
- Java Arrays
- Java One Dimensional Array
- Java Multidimensional Array
- Java Programming Operators
- Java Operators
- Java Arithmetic Operators
- Java Increment Decrement
- Java Bitwise Operators
- Java Left Shift
- Java Right Shift
- Java Relational Operators
- Java Boolean Logical Operators
- Java Ternary(?) Operator
- Java Operator Precedence
- Java Control Statements
- Java Decision Making
- Java if if-else if-else-if
- Java switch Statement
- Java Loops
- Java while Loop
- Java do-while Loop
- Java for Loop
- Java for-each Loop
- Java Nested Loops
- Java break Statement
- Java continue Statement
- Java Class Object Method
- Java Classes and Objects
- Java Class
- Java Object
- Java new Operator
- Java Methods
- Java Constructors
- Java this Keyword
- Java Stack
- Java Overloading Recursion
- Java Method Overloading
- Java Constructor Overloading
- Java Object as Parameter
- Java Call by Value Reference
- Java Returning Objects
- Java Recursion
- Java Modifier Types
- Java Encapsulate Poly String
- Java Encapsulation
- Java Polymorphism
- Java Nested Inner Class
- Java Strings
- Java Command Line Arguments
- Java Variable Length Arguments
- Java Inheritance Abstraction
- Java Inheritance
- Java super Superclass
- Java Multilevel Hierarchy
- Java Method Overriding
- Java Abstraction
- Java Packages Interfaces
- Java Packages
- Java Access Protection
- Java Import Statement
- Java Interfaces
- Java Programming Exceptions
- Java Exception Handling
- Java try catch
- Java throw throws
- Java finally Block
- Java Built In Exceptions
- Java Exception Subclasses
- Java Chained Exceptions
- Java Multithreading
- Java Multithreading
- Java Thread Model
- Java Main Thread
- Java Create Thread
- Java Thread Priorities
- Java Synchronization
- Java Inter Thread Communication
- Java Suspend Resume Stop Thread
- Java Get Thread State
- Java Enum Autobox Annotation
- Java Enumerations
- Java Type Wrappers
- Java Autoboxing
- Java Annotation
- Java Marker Annotations
- Java Single Member Annotation
- Java Built In Annotations
- Java Type Annotations
- Java Repeating Annotations
- Java Data File Handling
- Java Files I/O
- Java Streams
- Java Read Console Input
- Java Write Console Output
- Java PrintWriter Class
- Java Read Write Files
- Java Automatically Close File
- Java Programming Advance
- Java Date and Time
- Java Regular Expressions
- Java Collections Framework
- Java Generics
- Java Data Structures
- Java Network Programming
- Java Serialization
- Java Send Email
- Java Applet Basics
- Java Documentation
- Java Programming Examples
- Java Programming Examples
Java break Statement
In Java, the break statement has these three uses :
- It terminates a statement sequence in a switch statement.
- It can be used to exit from a loop.
- It can be used as a "civilized" form of goto.
As we already discussed about the first uses, so here we only discuss about the last two uses.
Use break to Exit a Loop
By using keyword break, you can force quick termination of a loop, bypassing the conditional expression and any remaining code in the body of the loop. Once a break statement is encountered inside a loop, the loop is terminated and program control resumes at the next statement following the loop. Below is a simple example, demonstrates break to exit a loop :
Example - Use break to Exit From a for Loop
Here is an example program, showing how to use break statement to exit from a for loop in Java:
/* Java Program Example - Java break Statement */ // Using break to exit a loop public class JavaProgram { public static void main(String args[]) { for(int i=0; i<100; i++) { if(i == 10) break; System.out.println("i is " + i); } System.out.println("Loop complete."); } }
When the above Java program is compile and executed, it will produce the following output:
As you can see that the for loop is designed to run from 0 to 99, the break statement causes it to terminate early, when i becomes 10.
The break statement can be used with any of Java's loops, including intentionally infinite loops. For example, here is the preceding program coded by the use of a while loop.
Example - Use break to Exit From a while Loop
Here is an example program, showing how to use break statement to exit from a while loop in Java:
/* Java Program Example - Java break Statement * Use break to exit a while loop */ public class JavaProgram { public static void main(String args[]) { int i = 0; while(i<100) { if(i == 10) break; System.out.println("i is " + i); i++; } System.out.println("Loop completed."); } }
When the above program is compile and executed, it will produce the same output as above :
Whenever used inside a set of nested loops, the break statement will only break out of the innermost loop. For example :
Example - Use break to Exit From nested Loop
Here is an example program, showing how to use break statement to exit from nested loop in Java:
/* Java Program Example - Java break Statement * Use break in nested loops */ public class JavaProgram { public static void main(String args[]) { for(int i=0; i<3; i++) { System.out.print("Pass " + i + " : "); for(int j=0; j<100; j++) { if(j == 10) // terminate loop break; // if j is 10 System.out.print(j + " "); } System.out.println(); } System.out.println("Loops Completed."); } }
When the above Java program is compile and executed, it will produce the following output:
As you can see that the break statement in the inner loop only causes the termination of that loop only. The outer loop is unaffected.
Here are the two other points to remember about the break :
- You can also use more than one break statement in a loop. However, be careful. Too many break statements have the tendency to destructure your code.
- The break statement that terminates a switch statement affects only that switch statement and not any enclosing loops.
Use break as a Form of Goto
In addition to its uses with switch and loops, the break statement can also be employed by itself to provide a "civilized" form of goto statement.
Java doesn't have a goto statement because it provides a way to branch in an arbitrary and unstructured manner, usually makes goto-ridden code hard to understand and maintain. It also prohibits the certain compiler optimizations.
There are some places where goto is a important and legitimate construct for the flow control. For example, goto can be useful when you are exiting from deeply nested set of loops. To handle such situations, Java defines an expanded form of break statement. By using this form of break, you can, for example, break out of one or more blocks of code. These blocks need not be the part of the loop or a switch. They can be any block. Furthermore, you can specify precisely where the execution will resume, because this form of break works with a label. As you will see, the break gives you the benefits of a goto without its problems.
labeled break Syntax
Below is the general form of the labeled break statement :
break label;
Most often, label is the name of a label that identifies a block of code. It can be a standalone block of code but it can also be a block that is the target of another statement. When this type of break executes, control is transferred out of named block. The labeled block must enclose the break statement, but it does not necessitated to be immediately enclosing block. It means, for example, that you can use a labeled break to exit from a set of nested blocks. But you can't use the break to transfer the control out of a block that does not enclose the break statement.
To name any block, put a label at the start of it. A label is any legal Java identifier followed by a colon.
Once you have labeled any block, you can use this label as the target of a break statement. Doing so, causes an execution to resume at the end of the labeled block. For example, here this program shows the three nested blocks, each with its own label. The break causes the execution to jump forward, past the end of the block labeled second, skipping the two println().
/* Java Program Example - Java break Statement * Use break as a civilized form of goto */ public class JavaProgram { public static void main(String args[]) { boolean t = true; first: { second: { third: { System.out.println("Before the break."); if(t) break second; // break out of second block System.out.println("This won't execute."); } System.out.println("This won't execute."); } System.out.println("This is after the second block."); } } }
When the above Java program is compile and executed, it will produce the following output:
One of the most common uses of a labeled break statement is to exit from the nested loops.
For example, in this program, the outer loop executes only once :
/* Java Program Example - Java break Statement * Using break to exit from nested loops */ public class JavaProgram { public static void main(String args[]) { outer: for(int i=0; i<3; i++) { System.out.print("Pass " + i + " : "); for(int j=0; j<100; j++) { if(j == 10) break outer; // exit both loops System.out.print(j + " "); } System.out.println("This will not print."); } System.out.println("\nLoops completed."); } }
When the above Java program is compile and executed, it will produce the following output:
As you can see here that when the inner loop breaks to the outer loop, both the loops have been terminated. Notice here that this example labels the for statement, which has a block of code as its target.
Always keep in mind that you can't break to any label which is not defined for an enclosing block.
More Examples
Here are some examples listed that uses break statement, you can go for.
« Previous Tutorial Next Tutorial »