Java quiz 36: Conditional statement with boolean

  Quizzes     Assignments     Puzzles     Easy exercises     Required knowledge  
< Java Quizzes   Green = Easy,  Blue = Normal,  Red = Hard
Select    31   32   33   34   35   36   37   38   39   40   41   By title 
>

This is a simple conditional statement using a boolean variable.

Java quiz 36: Conditional statement with boolean

Level: Easy

What happens if the following code is compiled and run?

public class MyClass
{
  public static void main(String[] args)
  {
    boolean isGood = false;
    for(int i = 0; i < 3; i++)
    {
      if(isGood)
      {
        System.out.print("x");
        isGood = false;
      }
      else
      {
        System.out.print("y");
        isGood = true;
      }
    }
  }
}
Author: Sar Maroof

Select the correct answer.

a. This program writes “yyy” to the standard output.
b. This program writes “yxy” to the standard output.
c. This program writes “yyx” to the standard output.
d. This program writes “xyx” to the standard output.
e. This program writes “xyy” to the standard output.
f. Illegal at compile time.
g. Illegal at run time.

Answer explanation

  1. The first if statement if(isGood) returns false, because the initial value of the boolean variable isGood is false. The statement System.out.print(“y”); writes y to the standard output.
  2. The statement isGood = true; changes the value of the variable isGood to true. The next time the statement if(isGood) returns true and the statement System.out.print(“x”);
    writes x to the standard output. The statement isGood = false; assigns false to the variable isGood.
  3. The next time when the statement if(isGood) is executed, y is written to the standard output.

The correct answer is: b.




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 *