Oracle Certified Professional Java Se 11 Developer · Free Practice Question Medium
Question 51
Question ID: UKOCP80735
Consider below code:
- package com.udayankhattry.ocp;
- import java.time.LocalDate;
- public class Test {
- public static void main(String[] args) {
- LocalDate d1 = null;
- //Value of d1 is successfully extracted from a DB
- //Line n1
- calculate(d1);
- //Line n2
- }
- public static void calculate(LocalDate date1) {
- //Complex code
- }
- }
Assume that the given code successfully extracts the value of d1 from a database and at Line n1, d1 is not null.
Which of the following statement is correct?
- A Value of d1 at Line n1 and Line n2 will always be same
- B Value of d1 at Line n1 and Line n2 may differ
- C At Line n2, value of d1 may be null
- D Code inside method calculate(LocalDate) may assign a new LocalDate instance to d1
Reveal correct answer
Correct answer: A
Explanation
UKOCP80735:
Classes of new Java Date and Time API are immutable.
At Line n1, d1 refers to valid LocalDate instances. As, d1 refers to an immutable instance, hence calculate(d1); will not be able to change the contents of instance, referred by d1.
When code reaches Line n2, there will not be any changes to the object referred by d1.
Let's check all the options one by one:
Value of d1 at Line n1 and Line n2 will always be same
✓ As per above explanation.
Value of d1 at Line n1 and Line n2 may differ
✗ As per above explanation.
At Line n2, value of d1 may be null
✗ It is mentioned in the question, that at Line n1, d1 is not null. calculate(d1); method cannot make d1 to refer to null or any other object, hence at Line n2, d1 cannot be null.
Code inside method calculate(LocalDate) may assign a new LocalDate instance to d1
✗ d1 is a local variable of main(String[]) method, hence calculate(LocalDate) method cannot assign a new LocalDate instance to d1
Check below link and section:
https://www.oracle.com/java/technologies/javase/seccodeguide.html
Guideline 6-1 / MUTABLE-1: Prefer immutability for value types
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
