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 questionsThe 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.
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.
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.
Keep practicing
Take the free 1Z0-809 practice test
Ten exam-style questions with answers and explanations, plus the exam facts and study guides.
More questions
Other 1Z0-809 practice questions
- Question 2Given: class Student { String course, name, city; public Student (String name, String cou…
- Question 3Given: class Worker extends Thread { CyclicBarrier cb; public Worker(CyclicBarrier cb) { …
- Question 4Given the code fragment: Path file = Paths.get (“courses.txt”); // line n1 Assume the cou…
- Question 5Given that /green.txt and /colors/yellow.txt are accessible, and the code fragment: Path …
- Question 6Given the code fragment:List<String> empDetails = Arrays.asList(“100, Robin, HR”,“200, Ma…
- Question 7Given the code fragment: List str = Arrays.asList (“my”, “pen”, “is”, “your’, “pen”); Pre…
