Jump Statements in Java

Advertisements

Java Jump Statements

Jump statements are used to interrupt the normal flow of program.

Types of Jump Statements are:

  • break
  • continue
  • labelled loop

break statement

break statement is used inside loop or switch statement. When compiler finds the break statement inside a loop, compiler will abort the loop and continue to execute statements followed by loop.

Example of break statement


//BreakStatementDemo.java

    class BreakStatementDemo
    {
        public static void main(String args[])
        {
            int a=1;

            while(a<=10)
            {
                if(a==5)
                    break;

                System.out.print("\n\tStatement : " + a);
                a++;

            }

            System.out.print("\n\tEnd of Program.");
        }
    }

    Output :

              Statement 1.
              Statement 2.
              Statement 3.
              Statement 4.
              End of Program.

The above program will abort the loop when the value of a reaches upto 5 and skip all statements present in loop.

continue statement

continue statement is also used inside loop. When compiler finds the break statement inside a loop, compiler will skip all the followling statements in the loop and resume the loop.

Example of continue statement


//ContinueStatementDemo.java

    class ContinueStatementDemo
    {
        public static void main(String args[])
        {
            int a=0;

            while(a<10)
            {

                a++;

                if(a==5)
                    continue;

                System.out.print("\n\tStatement " + a);

            }
            System.out.print("\n\tEnd of Program.");
    }

    Output :

              Statement 1.
              Statement 2.
              Statemnet 3.
              Statement 4.
              Statement 6.
              Statement 7.
              Statement 8.
              Statement 9.
              Statement 10.
              End of Program.

The above program will skip all statements present in loop when the value of a reaches upto 5 and continue the loop from 6 to 10.

Java Labelled Loop

According to nested loop, if we put break statement in inner loop, compiler will jump out from inner loop and continue the outer loop again. What if we need to jump out from the outer loop using break statement given inside inner loop? The answer is, we should define lable along with colon(:) sign before loop. More info.

Advertisement