Java puzzle 16: Conditional statements within a loop

<< Java Puzzles   Green = Easy,  Blue = Normal,  Red = Hard
 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 

Here is the puzzle of today, which demonstrates a conditional statement within a loop.

Java puzzle 16: Conditional statements within a loop

Level: Normal

What is the output of this program and why?

public class MyClass
  public static void main(String[] args)
    for(int i = 0; i < 4; i++)
      if(i > 2)
        System.out.print("y ");
Author: Sar Maroof

Answer explanation

  1. The loop is repeated 4 times, because the initial value of the variable i is 0 and the body of the loop is executed as long as i is smaller than 4.
  2. When i is equal to 0, the body of the loop is executed. The statement if(i > 2) returns false. Therefore the else block is executed and y is written to the standard ouput.
  3. When i is equal to 1 and 2, y is written to the standard output see the explanation of the step 2.
  4. When i is equal to 3 the statement if(i > 2) returns true. Therefore x is written to the standard output.
  5. The correct answer is that this program writes yyyx to the standard output.

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 *