Java puzzle 29: Loops and branching statements

  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 
>

This Java puzzle demonstrates a combination of branching statements.

Java puzzle 29: Loops and branching statements

Level: Normal

What is the output of the following code?

public class MyClass
{
  static int x;
  
  public static void main(String[] args)
  {
    for(int i = 0; i < 5; i++)
    {
      if(i == 2)
      {
        break;
      }
      else
      {
        return;
      }
      x += 3;
    }
    System.out.println(x);
  }
}
Author: Sar Maroof

Answer explanation

The statement x += 3; is unreachable. When the value of the variable i is equal to 2 the statement break; terminates the loop.
For other values of i the statement return; terminates the execution of the code.
Therefore the code doesn’t compile.





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 *