Java OCA OCP Practice Question 622

Question

What will be the result of attempting to compile and run the following class?

public class Main{ 
   public static void main (String args []){ 
      if  (true) 
      if  (false) 
      System .out.println ("True False"); 
      else 
      System .out.println ("True True"); 
    } 
} 

Select 1 option

  • A. The code will fail to compile because the syntax of the if statement is not correct.
  • B. The code will fail to compile because the values in the condition bracket are invalid.
  • C. The code will compile correctly and will not display anything.
  • D. The code will compile correctly and will display True True.
  • E. The code will compile correctly but will display True False


Correct Option is  : D

Note

This code can be rewritten as follows:

public class Main{ 
    public static void main (String args [])  { 
        if  (true)  { 
            if  (false)  { 
                System .out.println ("True False"); 
             } else  { 
                System .out.println ("True True"); 
             } //  ww  w  .ja  v a 2s  .  c o  m
         } 
     } 
} 

Notice how the last "else" is associated with the last "if" and not the first "if".

Now, the first if condition returns true so the next 'if' will be executed.

In the second 'if' the condition returns false so the else part will be evaluated which prints 'True True'.




PreviousNext

Related