Java OCA OCP Practice Question 1137

Question

What will the following code print?

public class Main {
   public static void main(String args[]) {
      boolean flag = true;
      if (flag = false) {
         System.out.println("1");
      } else if (flag) {
         System.out.println("2");
      } else if (!flag) {
         System.out.println("3");
      } else//from  w ww.jav a2  s.c o  m
         System.out.println("4");

   }
}

Select 1 option 

A. 1 
B. 2 
C. 3 
D. 4 
E. Compilation error. 


Correct Option is  : C

Note

At the beginning, flag is true.

In the first if, we do flag = false.

It is not flag == false.

It is a single =, which assigns false to flag.

Thus, flag becomes false and the condition becomes false therefore 1 is not printed.

In the first 'else if', since flag is false, 2 is not printed.

In second 'else if', !flag implies !false, which is true, so 3 is printed.

Since an else-if condition has been satisfied, the last else is not executed.




PreviousNext

Related