Break Statement

The break Statement

The break statement has two forms: labeled and un-labeled.

Un-labeled break

An unlabeled break statement terminates the innermost switch, for, while, or do-while statement.

Run The Application

Right click to the BreakDemo class; select Run As -> Java Application.

Output

Labeled break

Labeled break terminates an outer statement. The following program is similar to the previous program, but uses nested for loops to search for a value in a two-dimensional array. When the value is found, a labeled break terminates the outer for loop (labeled “search”):

Run The Application

Right click to the BreakWithLabelDemo class; select Run As -> Java Application.

Output

The continue Statement

The continue statement skips the current iteration of a for, while , or do-while loop. The unlabeled form skips to the end of the innermost loop’s body and evaluates the Boolean expression that controls the loop. The following program steps through a String, counting the occurences of the letter “o”. If the current character is not a p, the continue statement skips the rest of the loop and proceeds to the next character. If it is a “o”, the program increments the letter count.

Run The Application

Right click to the ContinueDemo class; select Run As -> Java Application.

Output

The return Statement

The return statement exits from the current method, and control flow returns to where the method was invoked. The return statement has two forms: one that returns a value, and one that doesn’t. To return a value, simply put the value (or an expression that calculates the value) after the return keyword.

The data type of the returned value must match the type of the method’s declared return value. When a method is declared void, use the form of return that doesn’t return a value.