1Z0-809 practice question 14 of 25

Given the code fragment: LocalDate valentinesDay =LocalDate.of(2015, Month.FEBRUARY, 14); LocalDate nextYear = valentinesDay.plusYears(1); nextYear.plusDays(15); //line n1 System.out.println(nextYear); What is the result?

Full set: 196 questions
Answer options
A: 2016-02-14 Correct answer
B: A DateTimeException is thrown.
C: 2016-02-29
D: A compilation error occurs at line n1.
Correct Answer:
A. 2016-02-14
Explanation

The classes in the java.time package, including LocalDate, are immutable. When a method like plusYears() or plusDays() is called on a LocalDate object, it does not change the state of that object. Instead, it returns a new LocalDate object with the modified value. In the code, the line nextYear.plusDays(15); calculates a new date but its result is not assigned to any variable. Therefore, the nextYear variable continues to reference the object representing 2016-02-14, which is what gets printed.

Why Incorrect

B. A DateTimeException is not thrown because all date calculations are valid. 2016 is a leap year, so February 29th is a valid date, but this is irrelevant as the result is discarded.
C. The result is not 2016-02-29 because the return value of nextYear.plusDays(15) is ignored, and the nextYear variable itself is not modified.
D. The code compiles successfully. Calling a method on an object and not using its return value is perfectly valid syntax in Java.

References

1. Oracle, "Java SE 8 Date and Time," The Java Tutorials. The section on "Date-Time API" principles states: "The classes in the java.time package are immutable."

2. Oracle, "LocalDate Class Java SE 8," java.time package documentation. The documentation for the plusDays(long daysToAdd) method specifies its return value: "a LocalDate based on this date with the days added, not null." This confirms a new object is returned.

3. Gosling, J., Joy, B., Steele, G., Bracha, G., & Buckley, A. (2015). The Java® Language Specification, Java SE 8 Edition. Section 4.12.3, "Kinds of Variables," implicitly supports the concept that nextYear is a reference that is not changed by the method call on the object it refers to.

Scroll to Top