Java OCA OCP Practice Question 629

Question

What is the output of the following application?

package mypkg; //from w  w  w  . ja va2  s  . co  m
abstract class Pet { 
   protected int count; 
   public abstract int getCount(); 
} 

public class Main extends Pet { 
   private int age; 
   public Main(int age) { this.age = age; } 
   public int getCount() { return this.age/count; } 
   public static void main(String[] pondInfo) { 
      Pet p = new Main(5); 
      System.out.print(p.getCount()); 
   } 
} 
  • A. 0
  • B. 5
  • C. The code does not compile.
  • D. The code compiles but throws an exception at runtime.


D.

Note

The code compiles without issue, so Option C is incorrect.

The key here is noticing that count, an instance variable, is initialized with a value of 0.

The getCount() method ends up computing 5/0, which leads to an unchecked ArithmeticException at runtime, making Option D the correct answer.




PreviousNext

Related