JUMP STATEMENTS in JAVA


JUMP STATEMENTS

                                                                                        

Java supports three jump statements: break, continue, and return. These statements transfer control to another part of your program.

1. break.
2. continue.
3. return.

1 The break statement


·         This statement is used to jump out of a loop.
·         On encountering a break statement within a loop, the execution continues with the  next statement outside the loop.
·         The remaining statements which are after the break and within the loop are skipped.
·         Break statement can also be used with the label of a statement.
·         A statement can be labeled as follows.
statementName : SomeJavaStatement

·         When we use break statement along with label as
break statementName;

An example of break statement

class break1
{
public static void main(String args[])
{
int i = 1;
while (i<=10)
{
System.out.println("\n" + i);
i++;
if (i==5)
{
break;
}
} }}
Output :
1
2
3
4
An example of break to a label
class break3
{
public static void main (String args[])
{
boolean t=true;
a:
{
b:
{
c:
{
System.out.println("Before the break");
if(t)
break b;
System.out.println("This will not execute");
}
System.out.println("This will not execute");
}
System.out.println("This is after b");
}
}
}

Output :
Before the break
This is after b

2 Continue statement

·         This statement is used only within looping statements.
·         When the continue statement is encountered, the next iteration starts.
·         The remaining statements in the loop are skipped. The execution starts from the top of loop again.
·          
The program below shows the use of continue statement.

class continue1
{
public static void main(String args[])
{
for (int i=1; i<1=0; i++)
{
if (i%2 == 0)
continue;

System.out.println("\n" + i);
}
}
}
Output :
1
3
5
7
9
3

3. The return statement

·         The last control statement is return. The return statement is used to explicitly return from a method.
·         That is, it causes program control to transfer back to the caller of the method.
·         The return statement immediately terminates the method in which it is executed.

The program below shows the use of return statement.

class Return1
{
public static void main(String args[])
{
boolean t = true;
System.out.println("Before the return.");
if(t)
return;       // return to caller
System.out.println("This won't execute.");
}
}
Output :
Before the return.

Comments