Java quiz 35: Easy conditional statements

  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   By title 
>

Here below is an easy conditional statement’s quiz.

Java quiz 35: Easy conditional statements

Level: Easy
What happens if the following code is compiled and run?

public class MyClass
{
  public static void main(String[] args)
  {
    int x = 1;
    int y = 4;
    if(y++ == 4)
    {
      x += 4;
      if(y == x)
      {
        x += 2;
        if(x > y)
        {
          x++;
        }
      }
      System.out.println(x);
    }
  }
}
Author: Sar Maroof

Select the correct answer.

a. This program writes “1” to the standard output.
b. This program writes “7” to the standard output.
c. This program writes “8” to the standard output.
d. This program writes “4” to the standard output.
e. This program writes “0” to the standard output.

Answer explanation

  1. The first condition if(y++ == 4) returns true, because y is incrimented by one after the evaluation.
  2. The statement x += 4; increments the value of x by 4, so x = 1 + 4 = 5.
  3. The value of y is now equal to 5.
  4. The condition if(y == x) returns true. So, x += 2; increments the value of x by 2, x = 5 + 2 = 7.
  5. The condition if(x > y) returns true, because x is greater than y. So, the statement x++; increments the value of x by one, x = 7 + 1 = 8.

The correct answer is: c.

The second edition of Learn Java and Master Writing Code is easy to understand, organized to learn Java voor beginners and it guides readers to master Java code by solving more than 100 exercises and assignments. This book explains each chapter properly before starting with the exercises and the assignments. Available on Amazon. See inside the book here!




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 *