Select three correct statements about the following code. public class Question20 { public static void main(String[] args) { Question20 myref = new Question20Sub(); try{ myref.test(); }catch(Exception e){} } void test() throws Exception{ System.out.println("In Question20"); throw new Exception(); } } class Question20Sub extends Question20 { void test() { System.out.println("In Question20Sub"); } }

  1. The try-catch block that encloses myref.test(); is mandatory for the code to compile.

  2. Prints: In Question20

  3. Prints: In Question20Sub

  4. Method test() in class Question20Sub has no obligation to declare a throws clause.

  5. An exception is thrown at runtime.


Correct Option: A,C,D

AI Explanation

To analyze the given code and determine the correct statements, let's go through each option:

Option A) The try-catch block that encloses myref.test(); is mandatory for the code to compile. This statement is correct. The test() method in the Question20 class throws an exception. If the try-catch block is not included, the code will generate a compile-time error because the exception is not handled.

Option B) Prints: In Question20 This statement is incorrect. Since the test() method is overridden in the Question20Sub class, and the test() method in Question20Sub does not throw an exception, the code will execute the test() method in Question20Sub, which prints "In Question20Sub".

Option C) Prints: In Question20Sub This statement is correct. As mentioned above, the test() method in Question20Sub is executed, and it prints "In Question20Sub".

Option D) Method test() in class Question20Sub has no obligation to declare a throws clause. This statement is correct. The test() method in Question20Sub does not declare a throws clause, indicating that it does not throw any checked exceptions. In Java, subclasses are not required to declare checked exceptions that are not declared by the superclass.

Option E) An exception is thrown at runtime. This statement is incorrect. Although the test() method in Question20 throws an exception, it is caught by the try-catch block in the main method. Therefore, no exception will be thrown at runtime.

To summarize:

Option A) This option is correct because the try-catch block is mandatory for the code to compile. Option B) This option is incorrect because it prints "In Question20Sub" instead of "In Question20". Option C) This option is correct because it prints "In Question20Sub". Option D) This option is correct because the test() method in Question20Sub has no obligation to declare a throws clause. Option E) This option is incorrect because no exception is thrown at runtime.

The correct statements are A, C, and D.

Find more quizzes: