Java OCA OCP Practice Question 1393

Question

What is the result of compiling and executing the following application?

package ranch; //from  www . j  a  v a2s.c  o  m
public class Main { 
   private int m = 5; 
   private double ship = m < 2 ? 1 : 10;  // g1 

   public void m() { 
      if(ship>1) { 
         System.out.println("Goodbye"); 
      } if(ship<10 && m>=2) 
         System.out.println("Hello");  // g2 
      else 
         System.out.println("See you again"); 
   } 

   public static final void main(String... stars) { 
      new Main().m(); 
   } 
} 
  • A. It only prints Hello.
  • B. It only prints Goodbye.
  • C. It only prints See you again.
  • D. It does not compile because of line g1.
  • E. It does not compile because of line g2.
  • F. None of the above


F.

Note

The code compiles without issue, making Options D and E incorrect.

Applying the ternary ? : operator, the variable ship is assigned a value of 10.0.

The expression in the first if-then statement evaluates to true, so Goodbye is printed.

Note that there is no else statement between the first and second if-then statements, therefore the second if-then statement is executed.

The expression in the second if-then statement evaluates to false, so the else statement is called and See you again is also printed.

Option F is the correct answer, with two statements being printed.




PreviousNext

Related