Turn Desktop View Off
by Dinesh Thakur

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

Break

 

The break construct is used to break out of the middle of loops: for, do, or while loop. When a break statement is encountered, execution of the current loops immediately stops and resumes at the first statement following the current loop. That is, we can force immediate termination of a loop, bypassing any remaining code in the body of the loop.

/* Print 1 to 10 using Break Statement Java Example*/

class BreakStatement

{

            public static void main(String args[] )

            {

                        int i;

                        i=1;

                        while(true)

                        {

                                    if(i >10) break;

                                    System.out.print(i+" ");

                                    i++;

                        }

            }

}

 

Continue

 

This command skips the whole body of the loop and executes the loop with the next iteration. On finding continue command, control leaves the rest of the statements in the loop and goes back to the top of the loop to execute it with the next iteration (value).

/* Print Number from 1 to 10 Except 5 */

class NumberExcept

{

            public static void main(String args[] )

            {

                        int i;

                        for(i=1;i<=10;i++)

                        {

                                    if(i==5) continue;

                                    System.out.print(i +" ");

                        }

            }

}

Above program will display the value of variable i from 1 to 4. When the value of variable i becomes 5, continue statement will skip the body of the loop following continue statement i.e. it skips System.out.println(i) statement and again executes the loop with the next iteration (value) i.e .. 6.

 

Return

 

This statement is mainly used in methods in order to terminate a method in between and return back to the caller method. It is an optional statement. That is, even if a method doesn't include a return statement, control returns back to the caller method after execution of the method. Return statement mayor may not return parameters to the caller method.