Oracle Certified Professional Java Se 8 Programmer · Free Practice Question Easy
Question 46
Given code of Test.java file:
- package com.udayan.ocp;
- import java.time.*;
- public class Test {
- public static void main(String [] args) {
- LocalTime t1 = LocalTime.now();
- LocalDateTime t2 = LocalDateTime.now();
- System.out.println(Duration.between(t1, t2));
- }
- }
What will be the result of compiling and executing Test class?
- A Program terminates successfully after displaying the output
- B Runtime Exception
- C Compilation error
Reveal correct answer
Correct answer: A
Explanation
Signature of between method defined in Duration class is: 'Duration between(Temporal startInclusive, Temporal endExclusive)'.
As both LocalTime and LocalDateTime implement 'Temporal' interface, hence there is no compilation error.
If the Temporal objects are of different types as in this case, calculation is based on 1st argument and 2nd argument is converted to the type of 1st argument. It is easy to convert LocalDateTime to LocalTime.
Program executes successfully and terminates successfully after displaying the Duration object on to the console.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
