Jump Statements in JAVA

JAVA supports three types of jump statements break, continue and return. These statements transfer control to another part of the program.

break

Using break can force your loop to terminate immediately and skip the rest of the code in the loop. Thus, control will be passed to the code next to the loop.

Example:

class BreakExample {
public static void main(String args[]) {
for(int i=0; i<100; i++) {
if(i == 10) break;       // terminate loop if i is 10
System.out.println(“i: ” + i);
}
System.out.println(“Loop complete.”);
}
}

continue

When you are in loop and at some point you want to continue running loop. Moreover, you don’t want the code to be executed in loop then we’ll use continue. The statement, continue will pass the control to the condition from inside the loop (in first loop control will go to the increment/ decrement part).

Example:

class ContinueExample {
public static void main(String args[]) {
for(int i=0; i<10; i++) {
System.out.print(i + ” “);
if (i%2 == 0) continue;
System.out.println(“”);
}
}
}

Output:         0 1
2 3
4 5
6 7
8 9
This code uses the % operator to check if i is even. If it is, the loop continues without printing a newline. Here is the output from this program.

Here is the output from this program.

return

The statement return will be used in methods/ function to pass the control back to the caller method.

Caller Method will be discussed in method topic.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

Powered by WordPress.com.

Up ↑

%d bloggers like this: