Provide Best Programming Tutorials

break-continue-return Statement In Java

Jump

Java supports three jump statement:

  • break
  • continue
  • return

. These three statements transfer control to other parts of the program.

Break

In Java, the break is majorly used for:

  • Terminate a sequence in a switch statement (discussed above).
  • To exit a loop.
  • Used as a “civilized” form of goto.

Using break to exit a Loop

Using break, we can force immediate termination of a loop, bypassing the conditional expression and any remaining code in the body of the loop. Note: Break, when used inside a set of nested loops, will only break out of the innermost loop.

The code below won’t loop 100 times since a==10 will break the loop and print Since a==10 then break the loop.

public static void showJumpBreak() {
  int a = 10;
  for (int i = 0; i < 100; i++) {
    if (a == 10) {
      System.out.println("Since a==10 then break the loop");
      break;
    }
  }
}

Continue

Sometimes it is useful to force an early iteration of a loop. That is, you might want to continue running the loop but stop processing the remainder of the code in its body for this particular iteration. This is, in effect, a goto just past the body of the loop, to the loop’s end. The continue statement performs such an action.

The code below print odd number. Since we just wanna odd number so if the number is not odd then we don’t need to run the rest of the code then we just leave this loop and enter the next one.

It will print 1 3 5 7 9.

public static void showJumpContinue() {
  int a = 10;
  for (int i = 0; i < 10; i++) {
    if (i % 2 == 0) {
      continue;
    }
    // If number is odd, print it
    System.out.print(i + " ");
  }
}

Return

The return statement is used to explicitly return from a method. That is, it causes a program control to transfer back to the caller of the method.

The code below shows the keywordreturn usage since if statement will be executed so the code

System.out.println("This won't execute."); will not be executed.

public static void showJumpReturn() {
   boolean t = true;
   System.out.println("Before the return.");

   if (t) {
     return;
   }
   // Compiler will bypass every statement
   // after return
   System.out.println("This won't execute.");
 }

This Post Has 2 Comments

  1. Everything is very open with a clear explanation of the issues.

    It was truly informative. Your website is useful. Many thanks for sharing!

    1. Glad you like it! If you wish you can leave your email and you will get a newly added article notification!

Leave a Reply to my profile Cancel reply

Close Menu