nerdexam
Oracle

1Z0-819 · Question #177

Given: public class Main { public static void main(String[] args) { import java.time.LocalDate; import static java.time.DayOfWeek.*; var today = LocalDate.now().with(TUESDAY).getDayOfWeek(); switch…

The correct answer is B. Unknown. Option B would be correct if the code compiled, but there's a critical issue the question is testing: import statements in Java must appear at the top of the file, before any class declaration - they cannot be placed inside a method body. This means the code actually fails to…

Controlling Program Flow

Question

Given: public class Main { public static void main(String[] args) { import java.time.LocalDate; import static java.time.DayOfWeek.*; var today = LocalDate.now().with(TUESDAY).getDayOfWeek(); switch (today) { case SATURDAY: System.out.println("Weekend"); break; case MONDAY: case FRIDAY: System.out.println("Working"); break; default: System.out.println("Unknown"); } } } What is the result?

Options

  • AWorkingUnknown
  • BUnknown
  • CTuesdayUnknown
  • DThe compilation fails.
  • ETuesday
  • FWorking

How the community answered

(38 responses)
  • A
    3% (1)
  • B
    74% (28)
  • C
    3% (1)
  • D
    8% (3)
  • F
    13% (5)

Explanation

Option B would be correct if the code compiled, but there's a critical issue the question is testing: import statements in Java must appear at the top of the file, before any class declaration - they cannot be placed inside a method body. This means the code actually fails to compile, making D the true correct answer and suggesting an error in the answer key.

Setting that aside and examining the intended logic: LocalDate.now().with(TUESDAY) adjusts the current date to the nearest Tuesday (using DayOfWeek as a TemporalAdjuster), and .getDayOfWeek() then returns DayOfWeek.TUESDAY - a constant, not a String. The switch statement lists cases for SATURDAY, MONDAY, and FRIDAY, but has no case TUESDAY, so execution falls through to default and prints "Unknown".

The distractors fail for these reasons: A (WorkingUnknown) requires two prints but only one path executes; C/E (Tuesday) confuse the DayOfWeek enum with its string name - getDayOfWeek() returns the enum value, which can't be printed directly in that context; F (Working) would require the day to be MONDAY or FRIDAY; and while D is actually the most defensible answer given the import-inside-method error, the question intends to ignore that.

Memory tip: In Java, import belongs at the top of the file - think of it as the "guest list at the door," not something you check mid-conversation. And whenever you use .with(DayOfWeek.X), remember you get back that exact day of week - always ask yourself whether your switch actually has a matching case for it.

Topics

#switch statements#DayOfWeek enum#LocalDate with()#enum case matching

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice