Java puzzle 29: Loops and branching statements

<< Java Puzzles   Green = Easy,  Blue = Normal,  Red = Hard
 P25   P26   P27   P28   P29   P30 
 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)
      x += 3;
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.

If you found this difficult, you might consider reading my book Java quizmaster for beginners. It is easy to understand, organized to learn Java in 17 days and it guides you to master Java code by solving 105 quizzes and 117 assignments. This book explains each chapter properly before starting with exercises and assignments. It is available on Amazon. See inside the book here!

Please, leave your questions, feedback and suggestions in the comments below! offers a practical method to learn and improve your Java skills. It avoids unnecessary long boring theoretical explanations, but it uses many exercises and quizzes.

Sar Maroof is graduated from HBO Amsterdam "higher professional education". He is a professional computer programming teacher, gives master classes and publishes technical articles. His experience with developing software started from 2001 and he has worked as a software developer for several big as well as small companies and later as a freelancer. He is the author of Java quizmaster and Build a Java application in 7 days.

Books by Sar Maroof


 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 *

Sarmaroof © 2017