Java puzzle 25: return, break and continue

  Quizzes     Assignments     Puzzles     Easy exercises     Required knowledge  
< Java Puzzles   Green = Easy,  Blue = Normal,  Red = Hard
Select    01   02   03   04   05   06   07   08   09   10   11   12   13   14   15 
 16   17   18   19   20   21   22   23   24   25   26   27   28   29   30   By title 
>

Questions:
1. What is the output of the following code?
2. What is the output if you replace the return; statement with the break; statement?
3. What is the output if you replace the return; statement with the continue; statement?

Java puzzle 25: The difference between return, break and continue

Level: Normal

public class MyClass
{
  static int count = 0;
  
  void print()
  {
    int[] numbers = {2, 3, 4};
    outer:for(int x: numbers)
    {
      count++;
      inner:for(int n = 0; n < 5; n++)
      {
        count++;
        return;
        // break;
        // continue;
      }
    }
  }
  public static void main(String[] args)
  {
    new MyClass().print();
    System.out.print(count);
  }
}
Author: Sar Maroof

Answer explanation

The outer loop is repeated 3 times, because there are three elements in the array.

  • return:
    When the return statement is reached, the execution of the method print is terminated.
    By using the return statement the outer loop is executed once, and the inner loop is also executed once. That is because at the first execution of the inner loop the return statement is reached.
  • break: By using the the break lable, the outer loop is executed three times, but the inner loop is terminated each time when the break statement is reached.
    So, count = 3 (outer loop) + 1 x 3 (inner loop) = 6.
  • continue: By using the continue statement the outer loop is executed 3 times and by each execution of the outer loop the inner loop is executed 5 times.
    So, count = 3 (outer loop) + 5 x 3 (inner loop) = 18.

The correct answer is:
1. 2.
2. 6.
3. 18.





Sar Maroof is a professional software development teacher, gives master classes and publishes technical articles. He is also an expert software developer and worked for several big as well as small companies and later as a freelancer.

 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!

Leave a Reply

Your email address will not be published. Required fields are marked *