Oracle Certified Professional Java Se 11 Developer · Free Practice Question Easy
Question 36
Question ID: UKOCP42049
Given code:
- package com.udayankhattry.ocp;
- import java.text.*;
- import java.time.format.DateTimeFormatter;
- import java.util.Locale;
- public class Test {
- public static void main(String[] args) {
- var dateFormatter = DateTimeFormatter.ofPattern("dd-MM-uuuu"); //Line n1
- System.out.println(dateFormatter.parse("10-5-2019")); //Line n2
- var currFormatter = NumberFormat.getCurrencyInstance(Locale.US); //Line n3
- System.out.println(currFormatter.parse("$7.00")); //Line n4
- }
- }
What is the result?
- A Code compiles successfully and on execution no exception is thrown at runtime
- B Code compiles successfully and on execution an exception is raised by Line n2
- C Code compiles successfully and on execution an exception is thrown by Line n4
- D Line n2 causes compilation failure
- E Line n4 causes compilation failure
Reveal correct answer
Correct answer: E
Explanation
UKOCP42049:
Variable 'dateFormatter' infers to DateTimeFormatter type and variable 'currFormatter' infers to NumberFormat type.
parse(...) method defined in new Date/Time API such as LocalDate, LocalTime, LocalDateTime and DateTimeFormatter can throw java.time.DateTimeException (which is a RuntimeException) but parse(...) method defined in NumberFormat class declares to throw java.text.ParseException (which is a checked exception) and hence needs to follow declare or handle rule.
As main(...) method doesn't provide try-catch block around Lind n4 and also it doesn't declares to throw ParseException, so Line n4 causes compilation failure.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
