nerdexam
Oracle

1Z0-809 · Question #215

Given the code fragment: // Login time:2015-01-12T21:58:18.817Z instant loginTime = Instant.now(); Thread.sleep(1000); // Logout time:2015-01-12T21:58:19.880Z instant logoutTime = Instant.now()…

The correct answer is D. Logged out at: 2015-01-12T21:58:00Z. There is actually an error in this question's stated correct answer. Here's why: truncatedTo(ChronoUnit.MINUTES) strips everything below the minute unit - seconds and nanoseconds are zeroed out - so both times become 2015-01-12T21:58:00Z. Since both login (21:58:18) and logout…

Question

Given the code fragment: // Login time:2015-01-12T21:58:18.817Z instant loginTime = Instant.now(); Thread.sleep(1000); // Logout time:2015-01-12T21:58:19.880Z instant logoutTime = Instant.now(); loginTime = loginTime.truncatedTo(ChronoUnit.MINUTES); // line n1 logoutTime = logoutTime.truncatedTo(ChronoUnit.MINUTES); if (logoutTime.isAfter(loginTime)) System.out.println("Logged out at:"+logoutTime); else System.out.println("Can't logout"); What is the result?

Options

  • AA compilation error occurs at line n1.
  • BLogged out at: 2015-01-12T21:58:19.880Z
  • CCan't logout
  • DLogged out at: 2015-01-12T21:58:00Z

How the community answered

(66 responses)
  • A
    15% (10)
  • B
    8% (5)
  • C
    5% (3)
  • D
    73% (48)

Explanation

There is actually an error in this question's stated correct answer. Here's why:

truncatedTo(ChronoUnit.MINUTES) strips everything below the minute unit - seconds and nanoseconds are zeroed out - so both times become 2015-01-12T21:58:00Z. Since both login (21:58:18) and logout (21:58:19) fall within the same minute, they truncate to the same Instant. That means logoutTime.isAfter(loginTime) returns false (equal is not after), the else branch runs, and the actual output is "Can't logout" - option C, not D.

Why each option is wrong:

  • A - Instant.truncatedTo() is a valid method that accepts ChronoUnit values supported by Instant; it compiles fine.
  • B - The fractional seconds and raw seconds are stripped by truncatedTo; the original .880Z timestamp is never printed.
  • D - This would only be correct if login and logout spanned two different minutes, so the truncated values differed and isAfter returned true.

Memory tip: truncatedTo(ChronoUnit.MINUTES) = "everything after HH:MM becomes :00Z". When testing duration across a minute boundary, the values differ; within the same minute, they collapse to equal - and isAfter never returns true for equal values.

Note for exam takers: This question appears in several Java SE 8 practice banks with a known error. The timestamps given produce C; D would require the times to straddle a minute boundary (e.g., 21:58:5921:59:01).

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice