Java OCA OCP Practice Question 1156

Question

What is the output of the following application?

package mypkg; /*from w ww  .  j  av a2s  .  co  m*/
public class Main { 
        private static int price = 5; 
        public boolean sell() { 
           if(price<10) { 
              price++; 
              return true; 
           } else if(price>=10) { 
              return false; 
           } 
        } 
        public static void main(String[] cash) { 
           new Main().sell(); 
           new Main().sell(); 
           new Main().sell(); 
           System.out.print(price); 
        } 
} 
  • A. 5
  • B. 6
  • C. 8
  • D. The code does not compile.


D.

Note

The sell() method does not compile because it does not return a value if both of the if-then statements' conditional expressions evaluate to false.

While logically, it is true that price is either less than 10 or greater than or equal to 10, the compiler does not know that.




PreviousNext

Related