Friday, February 16, 2018

Java Break and Continue Statements with example

In this post you will learn about break and continue statements in java with some examples.
The break statement is used to "break" out of the innermost switch, for, while, or do-while statement body. When it is executed, a break statement causes the flow of control to jump to the next line after the loop or switch to the body containing the break.

The typical use of a break statement has the following simple syntax:
break;

The break statement can also be used in a labeled form to jump out of an outernested loop or switch statement. In this case, it has the syntax
break label;

where label is a Java identifier that is used to label a loop or switch statement. Such a label can only appear at the beginning of the declaration of a loop. There are no other kinds of "go to" statements in Java.

We illustrate the use of break statement in the following simple example:
public class Break
{
public static void main(String[] args)
{
for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
break;    // terminate loop if i is 5
}
System.out.print(i + " ");
}
System.out.println("stop the loop here");
}
}

Output:
1 2 3 4 stop the loop here

Continue Statement:
The other statement to explicitly change the flow of control in a Java program is the continue statement, which has the following syntax:
 
continue label;

where label is an optional Java identifier that is used to label a loop. As mentioned above, there are no explicit "go to" statements in Java. Likewise, the continue statement can only be used inside loops (for, while, and do-while). The continue statement causes the execution to skip over the remaining steps of the loop body in the current iteration (but then continue the loop if its condition is satisfied).

Example:

public class ContinueTest
{
public static void main(String[] args)
{
for (int i = 1; i <= 10; i++)
{
if (i % 2 == 0)
{
continue;    // skip next statement if i is even
}
System.out.println(i + " ");
}
}
}
Output:
1 3 5 7 9

No comments:

Post a Comment

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...