1. public static void parse(String str) { 12. try { 13. float f= Float.parseFloat(str); 14. } catch (NumberFormatException nfe) { 15. f= 0; 16. } finally { 17. System.out.println(f); 18. } 19. } 20. public static void main(String[] args) { 21. parse(”invalid”); 22. } What is the result?
  1. 0.0

  2. Compilation fails

  3. A ParseException is thrown by the parse method at runtime

  4. A NumberFormatException is thrown by the parse method at runtime


Correct Option: B

AI Explanation

To answer this question, let's go through each option to understand why it is correct or incorrect:

Option A) 0.0 - This option is incorrect because the variable f is declared and initialized inside the try block and is not accessible outside the try block. Therefore, it cannot be printed in the finally block.

Option B) Compilation fails - This option is correct. The code will not compile because the variable f is declared inside the try block and is not accessible outside the try block. Therefore, when trying to print f in the finally block, a compilation error will occur.

Option C) A ParseException is thrown by the parse method at runtime - This option is incorrect because the code does not handle a ParseException. Instead, it catches a NumberFormatException in the catch block.

Option D) A NumberFormatException is thrown by the parse method at runtime - This option is incorrect because the code does not throw a NumberFormatException. Instead, it catches a NumberFormatException in the catch block.

The correct answer is B. Compilation fails because the variable f is declared inside the try block and is not accessible outside the try block.

Find more quizzes: