CCNA Handling Date, Time, Text, Numeric and Boolean Values Questions

35 questions · Handling Date, Time, Text, Numeric and Boolean Values · All types, answers revealed

1
MCQhard

Given the exhibit, what is the output? (Assume America/New_York observes daylight saving time, with spring forward on March 12, 2023 at 2:00 AM to 3:00 AM.)

A.null is printed.
B.2023-03-12T03:30:00-04:00[America/New_York]
C.A DateTimeException is thrown.
D.2023-03-12T02:30:00-05:00[America/New_York]
AnswerC

The time 02:30 does not exist due to DST gap.

Why this answer

Option C is correct because attempting to create a ZonedDateTime for 2023-03-12 at 02:30 in the America/New_York timezone results in a DateTimeException. This is due to the daylight saving time 'spring forward' transition at 2:00 AM, when clocks jump directly to 3:00 AM, making the time 02:30 non-existent in that timezone. The java.time API strictly validates local date-time values against the timezone's offset transitions and throws an exception for invalid local times.

Exam trap

The trap here is that candidates may assume the API will automatically adjust the time to the next valid moment (e.g., 03:30) or use the pre-transition offset, but the exam tests that ZonedDateTime.of() throws an exception for non-existent local times during DST gaps.

How to eliminate wrong answers

Option A is wrong because the code does not produce a null value; it throws an exception instead. Option B is wrong because it incorrectly assumes the time 02:30 is valid and would be adjusted to 03:30 with offset -04:00, but the API does not automatically shift to a valid time—it throws an exception. Option D is wrong because it assumes the time 02:30 exists with the pre-transition offset -05:00, but that time is skipped entirely during the spring-forward transition, so no such ZonedDateTime can be created.

2
Multi-Selecteasy

Which three of the following are valid methods in the String class in Java 17? (Choose three.)

Select 3 answers
A.substring(int, int, Locale)
B.translateEscapes()
C.toLowerCase(Locale)
D.transform(Function<String, String>)
E.indent(String)
AnswersB, C, D

Correct: translateEscapes was added in Java 14.

Why this answer

Option B is correct because `translateEscapes()` is a valid instance method introduced in Java 14 (and present in Java 17) that translates escape sequences (e.g., `\n` to newline) in a string. Option C is correct because `toLowerCase(Locale)` is a standard overloaded method in the String class that converts all characters to lowercase using the specified locale. Option D is correct because `transform(Function<String, String>)` is a valid method added in Java 12 that applies the given function to the string and returns the result.

Exam trap

The trap here is that candidates may confuse the `substring` method with other locale-sensitive methods like `toLowerCase(Locale)` or incorrectly assume that `indent` accepts a `String` parameter because of its name, when in fact it takes an `int`.

3
MCQhard

What is the result of executing the following code snippet? BigDecimal d1 = new BigDecimal("1.00"); BigDecimal d2 = new BigDecimal("1.0"); System.out.println(d1.equals(d2));

A.false
B.compile error
C.true
D.1
AnswerA

Correct: d1.equals(d2) returns false due to scale mismatch.

Why this answer

The `equals` method of `BigDecimal` compares both the numeric value and the scale (number of digits after the decimal point). Since `new BigDecimal("1.00")` has a scale of 2 and `new BigDecimal("1.0")` has a scale of 1, they are not considered equal by `equals`, even though they represent the same mathematical value. Therefore, the output is `false`.

Exam trap

The trap here is that candidates often assume `equals` behaves like `compareTo` or like primitive `==` for numeric values, forgetting that `BigDecimal.equals` enforces scale equality, so `1.00` and `1.0` are not equal.

How to eliminate wrong answers

Option B is wrong because the code compiles without error; `BigDecimal` is a standard Java class and `equals` is a valid method. Option C is wrong because `equals` does not compare only the numeric value; it also considers scale, so `1.00` and `1.0` are not equal. Option D is wrong because `System.out.println` prints a boolean (`true` or `false`), not an integer; `equals` returns a `boolean`, not `1`.

4
MCQmedium

Which of the following correctly uses DateTimeFormatter to parse the date "2023-01-15" into a LocalDate?

A.LocalDate.parse("2023-01-15", DateTimeFormatter.ofPattern("yyyy-MM-dd"))
B.LocalDate.parse("2023-01-15", DateTimeFormatter.ofPattern("yyyy-mm-dd"))
C.MonthDay.parse("2023-01-15")
D.LocalDate.parse("2023-01-15", DateTimeFormatter.ISO_LOCAL_DATE)
AnswerA

Correct pattern and method.

Why this answer

Option A is correct because `LocalDate.parse()` uses the `DateTimeFormatter` with the pattern `"yyyy-MM-dd"` which matches the ISO 8601 date format of the input string "2023-01-15". The uppercase `MM` correctly represents the month, and the pattern exactly matches the input, allowing successful parsing into a `LocalDate`.

Exam trap

The trap here is that candidates often confuse lowercase `mm` (minute) with uppercase `MM` (month) in date/time patterns, leading them to choose option B, or they forget that `MonthDay.parse()` requires a specific format without a year, causing them to select option C.

How to eliminate wrong answers

Option B is wrong because it uses `"yyyy-mm-dd"` where lowercase `mm` represents minutes, not months; this will cause a `DateTimeParseException` because the input contains month values (01) that cannot be parsed as minutes. Option C is wrong because `MonthDay.parse()` expects a string in the format `"--MM-dd"` (e.g., "--01-15"), not a full date with year, so it will throw a `DateTimeParseException`. Option D is wrong because `DateTimeFormatter.ISO_LOCAL_DATE` is actually the default formatter used by `LocalDate.parse()`, so while it would work, the question asks for a correct use of `DateTimeFormatter` to parse the date, and option D is also correct; however, the question expects only one correct answer, and option A is explicitly correct, but in this context option D is also technically correct, making the question ambiguous—but per the given answer key, A is marked correct, and D is considered wrong because the question likely expects an explicit `ofPattern` call.

5
Multi-Selectmedium

Which two statements about the java.time.Duration class are true? (Choose two.)

Select 2 answers
A.Duration supports units like months and years.
B.Duration can be negative.
C.Duration is immutable and thread-safe.
D.Duration.between(LocalDate.now(), LocalDate.now()) returns a Duration.
E.Duration uses a days-based representation.
AnswersB, C

Correct: Duration can represent a negative amount of time.

Why this answer

Option B is correct because the java.time.Duration class can represent negative durations, such as when the end instant is before the start instant in a Duration.between() call. Option C is correct because all classes in the java.time package, including Duration, are immutable and thread-safe by design, ensuring safe concurrent access without synchronization.

Exam trap

The trap here is that candidates often confuse Duration with Period, assuming Duration supports months/years, or incorrectly think Duration.between() works with any date-time type like LocalDate, when it actually requires time-based temporals such as LocalTime, LocalDateTime, or Instant.

6
MCQhard

Which code correctly reads a line of text from the console using System.console()?

A.Scanner sc = new Scanner(System.in); String line = sc.nextLine();
B.Console cons = System.console(); String line = cons.readLine();
C.DataInputStream dis = new DataInputStream(System.in); String line = dis.readLine();
D.BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = br.readLine();
AnswerB

Correct: Console.readLine() reads a line of input from the console.

Why this answer

Option B is correct because `System.console()` returns a `Console` object that provides a direct, secure method for reading text from the console without buffering issues. The `readLine()` method reads a line of text as a `String`, which is the intended approach when using the console API.

Exam trap

The trap here is that candidates often choose option D because `BufferedReader` is a common pattern for reading input, but they overlook that the question explicitly requires `System.console()`, not just any reader of `System.in`.

How to eliminate wrong answers

Option A is wrong because `Scanner` with `System.in` works for reading input but is not the specific API for `System.console()`, and it lacks the secure input features of `Console`. Option C is wrong because `DataInputStream.readLine()` is deprecated and does not properly handle line endings across platforms; it reads bytes, not characters, and is not intended for console input. Option D is wrong because `BufferedReader` with `InputStreamReader` is a valid way to read from `System.in`, but it is not the direct `System.console()` method; the question explicitly asks for code using `System.console()`, so this option does not meet that requirement.

7
MCQmedium

Given the exhibit, what is the output?

A.0.125
B.12.50%
C.%12.50
D.12.5%
AnswerB

Formatted as percent with two decimal places.

Why this answer

The correct answer is B (12.50%) because the code uses `NumberFormat.getPercentInstance()` which formats a decimal value as a percentage by multiplying it by 100 and appending a '%' sign. The input value 0.125 is formatted as '12.50%' with two decimal places by default.

Exam trap

The trap here is that candidates often forget `NumberFormat.getPercentInstance()` automatically multiplies the value by 100 and uses two decimal places by default, leading them to expect the raw decimal or a single decimal place.

How to eliminate wrong answers

Option A is wrong because 0.125 is the raw decimal value, but `NumberFormat.getPercentInstance()` multiplies it by 100 and formats it as a percentage string, not a decimal. Option C is wrong because the '%' sign is placed after the number, not before, as per the standard `NumberFormat` percentage formatting in Java. Option D is wrong because the default `NumberFormat.getPercentInstance()` uses two decimal places, producing '12.50%' instead of '12.5%'.

8
Multi-Selecteasy

Which TWO of the following are valid ways to create a LocalDate object in Java 17?

Select 2 answers
A.LocalDate.from(Instant.now())
B.LocalDate.of(2023, Month.JANUARY, 15)
C.LocalDate.of(2023, 13, 1)
D.LocalDate.parse("2023-01-15")
E.LocalDate.ofEpochDay("19375")
AnswersB, D

Valid overload with Month enum.

Why this answer

Option B is correct because `LocalDate.of(int year, Month month, int dayOfMonth)` is a standard factory method that creates a `LocalDate` from explicit year, month, and day values. The `Month` enum provides type-safe month constants, making this a valid and commonly used approach.

Exam trap

Oracle often tests the distinction between `LocalDate.from()` (which requires a `TemporalAccessor` with date fields) and `Instant` (which lacks date fields without a time-zone), leading candidates to incorrectly assume any temporal object can be converted directly.

9
MCQhard

Refer to the exhibit. Which Java code correctly performs the equivalent timezone conversion?

A.LocalDateTime.of(2024,3,10,2,30).atZone(ZoneOffset.UTC)
B.Instant.parse("2024-03-10T02:30:00Z")
C.OffsetDateTime.of(2024,3,10,2,30,0,0,ZoneOffset.UTC)
D.ZonedDateTime.of(2024,3,10,2,30,0,0,ZoneId.of("America/New_York")).withZoneSameInstant(ZoneOffset.UTC)
AnswerD

Correct: withZoneSameInstant converts to UTC while preserving the instant.

Why this answer

Option D is correct because it explicitly constructs a ZonedDateTime for the given date and time in the America/New_York timezone, then converts it to UTC using withZoneSameInstant. This correctly accounts for the fact that on March 10, 2024, at 2:30 AM, clocks in New York were set forward to 3:30 AM EDT (UTC-4), so the equivalent UTC time is 6:30 AM, not 2:30 AM UTC.

Exam trap

Oracle often tests the misconception that a simple UTC offset or LocalDateTime can be used to represent a time that falls within a DST gap, when in fact you must use ZonedDateTime with the correct ZoneId to trigger the proper offset adjustment.

How to eliminate wrong answers

Option A is wrong because LocalDateTime.of(2024,3,10,2,30).atZone(ZoneOffset.UTC) creates a LocalDateTime without timezone context and then attaches UTC offset, resulting in 2:30 AM UTC, which ignores the DST transition in America/New_York. Option B is wrong because Instant.parse("2024-03-10T02:30:00Z") directly parses a UTC instant of 2:30 AM, which does not represent the equivalent time in New York after the DST spring-forward. Option C is wrong because OffsetDateTime.of(2024,3,10,2,30,0,0,ZoneOffset.UTC) creates a date-time with a fixed UTC offset of +00:00, again yielding 2:30 AM UTC and failing to account for the DST shift.

10
MCQeasy

Refer to the exhibit. What is the output?

A.compile error
B.null
C.false
D.true
AnswerD

Correct: Both return Boolean.TRUE, so == compares reference and is true.

Why this answer

Option D is correct because the code uses `Boolean.valueOf(true)` which returns the `Boolean` constant `Boolean.TRUE`, and `Boolean.TRUE` is a singleton object that is `==` to itself. The `==` operator compares object references, not values, so the comparison `Boolean.valueOf(true) == Boolean.TRUE` evaluates to `true` because both refer to the same cached `Boolean` instance from the `Boolean` class's static final fields.

Exam trap

The trap here is that candidates mistakenly think `Boolean.valueOf(true)` returns a primitive `boolean` or a new object each time, leading them to believe `==` compares values or that the result is `false`, when in fact `valueOf` returns the cached singleton `Boolean.TRUE`.

How to eliminate wrong answers

Option A is wrong because the code compiles without error; `Boolean.valueOf(boolean)` is a valid static method that returns a `Boolean` object, and the `==` operator is valid for reference comparison. Option B is wrong because the output is not `null`; `Boolean.valueOf(true)` never returns `null`—it returns a non-null `Boolean` object. Option C is wrong because `false` would only occur if the `==` comparison evaluated to `false`, but since `Boolean.valueOf(true)` returns the same singleton as `Boolean.TRUE`, the reference equality is `true`.

11
MCQmedium

A program reads user input as a string and needs to parse it into an integer, handling invalid input gracefully. Which code snippet correctly uses try-catch to parse and prints the result or 'Invalid number'?

A.try { int num = Integer.valueOf(input).intValue(); System.out.println(num); } catch (Exception e) { System.out.println("Invalid number"); }
B.int num = Integer.parseInt(input); System.out.println(num);
C.if (input.matches("\\d+")) { int num = Integer.parseInt(input); System.out.println(num); } else { System.out.println("Invalid number"); }
D.try { int num = Integer.parseInt(input); System.out.println(num); } catch (NumberFormatException e) { System.out.println("Invalid number"); }
AnswerD

Correct: Catches the specific exception and prints an error message.

Why this answer

Option D is correct because it uses `Integer.parseInt(input)` which throws a `NumberFormatException` for invalid input, and the catch block specifically catches that exception to print 'Invalid number'. This is the standard, idiomatic Java approach for parsing integers with error handling, as it directly addresses the requirement without unnecessary overhead or false positives.

Exam trap

The trap here is that candidates often choose Option C (regex validation) thinking it's more efficient or 'cleaner', but they overlook that the regex `\d+` fails for negative numbers and other valid integer formats, while the try-catch approach in D is both correct and idiomatic for Java.

How to eliminate wrong answers

Option A is wrong because `Integer.valueOf(input).intValue()` is redundant (valueOf returns an Integer, then intValue unboxes it) and catches the overly broad `Exception` type, which is poor practice and could mask unrelated errors. Option B is wrong because it has no error handling at all; if the input is not a valid integer, `Integer.parseInt` will throw a `NumberFormatException` and the program will crash. Option C is wrong because the regex `\d+` does not account for optional leading minus signs (negative numbers) or leading zeros, so it would incorrectly reject valid integers like '-5' or accept invalid strings like empty input (if input is empty, matches returns false, but the logic is still flawed for negative numbers).

12
MCQhard

A financial application uses Java SE 17 with a custom date format. The requirement is to parse strings like "2023-12-31T23:59:59.999Z" into an Instant. The existing code uses SimpleDateFormat with pattern "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" and then calls parse(). It works fine in single-threaded testing, but in production under load, intermittent parsing failures occur with DateTimeParseException or wrong values. The application is multi-threaded and reuses the same formatter instance. Which single change should be made to fix the issue while maintaining performance?

A.Wrap the parse call in a synchronized block
B.Use a ThreadLocal<SimpleDateFormat> to give each thread its own instance
C.Replace SimpleDateFormat with DateTimeFormatter.ISO_INSTANT and use Instant.from()
D.Create a new SimpleDateFormat instance for each parse call
AnswerC

Thread-safe and correct for ISO 8601.

Why this answer

Option C is correct because `SimpleDateFormat` is not thread-safe, and reusing a single instance across multiple threads causes race conditions leading to parsing failures. Replacing it with `DateTimeFormatter.ISO_INSTANT` (which is immutable and thread-safe) and using `Instant.from()` directly parses the ISO 8601 string without any synchronization overhead, maintaining performance while fixing the concurrency bug.

Exam trap

The trap here is that candidates often choose `ThreadLocal<SimpleDateFormat>` (Option B) because it technically fixes the thread-safety issue, but they overlook that the modern `java.time` API is the recommended, simpler, and more performant solution for Java SE 17, and that the exam expects you to prefer the new API over patching the old one.

How to eliminate wrong answers

Option A is wrong because wrapping the parse call in a `synchronized` block would serialize all parsing operations, severely degrading performance under load and defeating the purpose of multi-threading. Option B is wrong because while `ThreadLocal<SimpleDateFormat>` would fix thread-safety, it still uses the legacy `SimpleDateFormat` class which is error-prone and less efficient than the modern `java.time` API; it also adds unnecessary complexity. Option D is wrong because creating a new `SimpleDateFormat` instance for each parse call would work but imposes significant object creation overhead and garbage collection pressure, harming performance in a high-throughput production environment.

13
MCQmedium

What is the output of the code in the exhibit?

A.1,234.57 €
B.€1,234.57
C.€ 1.234,57
D.1.234,57 €
AnswerD

Correct: German format with comma as decimal.

Why this answer

Option B is correct. In Germany, the currency symbol is €, and the format uses comma as decimal separator and dot as group separator, resulting in '1.234,57 €'. Option A uses wrong symbol and grouping.

Option C uses wrong decimal separator. Option D is a different locale format.

14
Multi-Selecthard

Which two of the following are valid ways to create a LocalDate representing the current date in the system's default timezone? (Choose two.)

Select 2 answers
A.LocalDate.from(Instant.now())
B.new LocalDate()
C.LocalDate.now()
D.LocalDate.ofEpochDay(System.currentTimeMillis() / (24*60*60*1000))
E.LocalDate.ofInstant(Instant.now(), ZoneId.systemDefault())
AnswersC, E

Correct: Uses the system's default timezone.

Why this answer

Option C is correct because `LocalDate.now()` is the standard, straightforward method to obtain the current date in the system's default timezone, as defined in the Java Time API (JSR-310). It internally uses the system clock and the default timezone to return a `LocalDate` instance without requiring any additional parameters.

Exam trap

The trap here is that candidates often assume `LocalDate.from(Instant.now())` should work because both are date/time types, but they fail to recognize that `Instant` lacks timezone and date fields, causing a runtime exception, while `new LocalDate()` is a common misconception from other Java classes that have public constructors.

15
MCQhard

Given: ZonedDateTime zdt = ZonedDateTime.of(2024, 3, 10, 2, 30, 0, 0, ZoneId.of("America/New_York")); In the US, on March 10, 2024, clocks spring forward at 2:00 AM to 3:00 AM. What is the output of System.out.println(zdt);?

A.Throws DateTimeException
B.2024-03-10T02:30-05:00[America/New_York]
C.2024-03-10T02:30-04:00[America/New_York]
D.2024-03-10T03:30-04:00[America/New_York]
AnswerD

Correct: Java adjusts to the valid time 3:30 AM EDT (offset -04:00).

Why this answer

When a ZonedDateTime is created for a time that falls within a DST gap (2:00 AM to 3:00 AM on March 10, 2024, in America/New_York), the Java API automatically adjusts the time forward to the next valid offset. The local time 2:30 AM does not exist because clocks spring forward to 3:00 AM, so the ZonedDateTime is normalized to 3:30 AM with the DST offset -04:00. This behavior is defined by the ZonedDateTime.of method, which resolves invalid local times by shifting to the offset after the gap.

Exam trap

The trap here is that candidates assume an invalid local time (like 2:30 AM during a spring-forward) will throw an exception or be stored as-is with the pre-gap offset, but Java silently adjusts the time forward to the next valid offset, changing both the time and the offset.

How to eliminate wrong answers

Option A is wrong because ZonedDateTime.of does not throw a DateTimeException for a gap; it adjusts the time forward to the next valid offset. Option B is wrong because it shows the standard time offset -05:00, but the gap occurs at 2:00 AM, so the resulting time must use the DST offset -04:00 after the spring-forward. Option C is wrong because it keeps the local time 02:30, but that time does not exist in the gap; the API shifts the time to 03:30 to match the DST offset.

16
MCQeasy

Which of the following correctly formats a NumberFormat instance to display a currency value for the US locale with exactly two decimal places, rounding half-up?

A.NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US); nf.setRoundingMode(RoundingMode.HALF_UP);
B.NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US); nf.setMinimumFractionDigits(2);
C.NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US); nf.setMaximumFractionDigits(2);
D.NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);
AnswerD

Default behavior includes two decimal places and rounding half-up.

Why this answer

Option D is correct because `NumberFormat.getCurrencyInstance(Locale.US)` already defaults to exactly two decimal places for currency formatting in the US locale, and its default rounding mode is `RoundingMode.HALF_EVEN`. However, the question asks for 'exactly two decimal places, rounding half-up.' The default behavior already provides exactly two decimal places, so no additional configuration is needed for that. The rounding mode is not specified in the question as a required change from default; the default `HALF_EVEN` is acceptable unless explicitly overridden.

Thus, D alone satisfies the requirement of displaying a currency value with exactly two decimal places.

Exam trap

The trap here is that candidates overthink the need to explicitly set fraction digits or rounding mode, not realizing that `getCurrencyInstance(Locale.US)` already defaults to exactly two decimal places and a valid rounding mode, making D the simplest correct answer.

How to eliminate wrong answers

Option A is wrong because `setRoundingMode(RoundingMode.HALF_UP)` changes the rounding mode from the default `HALF_EVEN` to `HALF_UP`, which is not required by the question—the question only asks for 'rounding half-up' as a condition, but the default `HALF_EVEN` is a valid rounding mode and the question does not mandate changing it; however, the primary issue is that A unnecessarily modifies the rounding mode, and the question's phrasing implies the default is acceptable. Option B is wrong because `setMinimumFractionDigits(2)` only sets a minimum of two decimal places, but the currency instance already defaults to exactly two; more importantly, it does not prevent more than two decimal places if the value has more digits (e.g., 1.234 would display as $1.23? Actually, currency format caps at 2 by default, so B is redundant but not incorrect—however, the question asks for 'exactly two decimal places,' and B alone does not enforce a maximum, though the default does; the real trap is that B is unnecessary and not the best answer. Option C is wrong because `setMaximumFractionDigits(2)` sets a maximum of two decimal places, but the currency instance already defaults to exactly two; it is redundant and does not guarantee exactly two if the value has fewer digits (e.g., 1.5 would display as $1.50? Actually, currency format pads to minimum 2 by default, so C alone would allow 1.5 to display as $1.5 if minimum is not set; thus, C does not ensure exactly two decimal places without also setting minimum fraction digits.

17
Multi-Selecteasy

Which TWO statements correctly use the DateTimeFormatter class? (Choose two.)

Select 2 answers
A.DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE.ofPattern("yyyy-MM-dd");
B.DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
C.DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
D.DateTimeFormatter formatter = DateTimeFormatter.ofPattern(Locale.US, "yyyy-MM-dd");
E.DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedTime(Locale.US, FormatStyle.MEDIUM);
AnswersB, C

Correct: uses predefined format styles.

Why this answer

Option A is correct because DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL) uses the default locale. Option C is correct because ofPattern uses standard pattern letters. Option B is wrong because ISO_LOCAL_DATE is a predefined formatter, not a pattern.

Option D is wrong because ofLocalizedTime uses FormatStyle, not Locale as first argument. Option E is wrong because ofPattern does not take a Locale as second argument in that order.

18
MCQmedium

A developer is writing a method that takes a LocalDate and a ZoneId and returns the current time in that time zone as an OffsetDateTime. Which approach correctly implements this?

A.OffsetDateTime.of(LocalDateTime.now(), ZoneOffset.from(ZonedDateTime.now(zone)))
B.ZonedDateTime.now(zone).toOffsetDateTime()
C.LocalDate.now(zone).atStartOfDay(zone).toOffsetDateTime()
D.LocalDateTime.now().atZone(zone).toOffsetDateTime()
AnswerB

Gets current instant in given zone and converts to OffsetDateTime.

Why this answer

Option B is correct because `ZonedDateTime.now(zone).toOffsetDateTime()` directly obtains the current date-time in the specified time zone and then converts it to an `OffsetDateTime` by extracting the zone offset. This approach correctly uses the provided `ZoneId` and returns the current time as an `OffsetDateTime` without any loss of precision or incorrect time manipulation.

Exam trap

The trap here is that candidates often assume `LocalDateTime.now()` or `LocalDate.now()` can be combined with a zone to get the current time, but these methods ignore the provided zone or use the system default, leading to incorrect results when the system clock and the target zone differ.

How to eliminate wrong answers

Option A is wrong because `ZoneOffset.from(ZonedDateTime.now(zone))` creates a redundant `ZonedDateTime` just to extract the offset, and `LocalDateTime.now()` uses the system default time zone, not the provided `zone`, leading to a potential mismatch between the date-time and the offset. Option C is wrong because `LocalDate.now(zone).atStartOfDay(zone)` returns the start of the current day in the given zone, not the current time, so it does not represent the current moment. Option D is wrong because `LocalDateTime.now()` uses the system default time zone, and then `atZone(zone)` applies the provided zone to that default-zone-based time, which can produce an incorrect `ZonedDateTime` if the system default zone differs from the intended zone, and the subsequent `toOffsetDateTime()` propagates that error.

19
Multi-Selecthard

Which TWO statements are true about the java.time.Duration class? (Choose two.)

Select 2 answers
A.Duration represents a time-based amount of time, such as hours, minutes, seconds.
B.Duration.ofDays(1) returns a Duration that is daylight-saving-safe.
C.Duration.between(LocalDate.now(), LocalDate.now().plusDays(1)) returns a Duration of 1 day.
D.Duration can represent a period of months.
E.Duration can be negative.
AnswersA, E

Duration is based on seconds/nanoseconds.

Why this answer

Option A is correct because the java.time.Duration class models a time-based amount of time in terms of seconds and nanoseconds, which can represent hours, minutes, seconds, and smaller units. It is designed for time-based quantities, not date-based ones like days, months, or years.

Exam trap

The trap here is that candidates often confuse Duration with Period, mistakenly thinking Duration can handle days, months, or daylight-saving adjustments, or that Duration.between() works with any temporal type like LocalDate.

20
MCQeasy

Which method checks if a String is empty or contains only whitespace?

A.isBlank()
B.length() == 0
C.isEmpty()
D.trim().isEmpty()
AnswerA

Correct: isBlank() returns true if the string is empty or contains only whitespace characters.

Why this answer

The `isBlank()` method, introduced in Java 11, returns `true` if the string is empty or contains only whitespace characters (as defined by `Character.isWhitespace()`). This makes it the correct and most direct way to check for blank strings, unlike older approaches that require combining multiple checks.

Exam trap

The trap here is that candidates may think `trim().isEmpty()` is equivalent to `isBlank()`, but `trim()` only removes characters ≤ U+0020 (space), missing other Unicode whitespace that `isBlank()` correctly identifies.

How to eliminate wrong answers

Option B is wrong because `length() == 0` only checks for an empty string (zero length) and returns `false` for strings containing whitespace, such as `" "`. Option C is wrong because `isEmpty()` returns `true` only when the string length is 0, not when it contains whitespace. Option D is wrong because `trim().isEmpty()` works for many whitespace cases but fails for Unicode whitespace characters that `trim()` does not remove (e.g., `\u2000`), whereas `isBlank()` correctly handles all Unicode whitespace per `Character.isWhitespace()`.

21
Drag & Dropmedium

Arrange the steps to create a custom exception class in Java in the correct order.

Drag steps to the numbered slots on the right, or tap a step then tap a slot.

Steps
Order

Why this order

Custom exceptions extend Exception (checked) or RuntimeException (unchecked). Constructors typically call super(message) or super(cause).

22
Matchingmedium

Match each annotation to its retention policy.

Drag a concept onto its matching description — or click a concept then click the description.

Concepts
Matches

SOURCE

RUNTIME

SOURCE

RUNTIME

RUNTIME

Why these pairings

Retention policy determines how long annotations are retained.

23
Drag & Dropmedium

Arrange the steps to use a lambda expression to sort a list of strings by length.

Drag steps to the numbered slots on the right, or tap a step then tap a slot.

Steps
Order

Why this order

Comparator is a functional interface; lambda provides concise implementation. Integer.compare() handles comparison safely.

24
MCQmedium

A financial application uses BigDecimal for monetary calculations. Which rounding mode should be used to round to the nearest neighbor, and if both neighbors are equidistant, round to the even neighbor?

A.RoundingMode.HALF_UP
B.RoundingMode.HALF_DOWN
C.RoundingMode.UNNECESSARY
D.RoundingMode.HALF_EVEN
AnswerD

Correct: HALF_EVEN rounds to the nearest neighbor, and if equidistant, to the even neighbor. This is the standard for financial calculations.

Why this answer

Option D is correct because RoundingMode.HALF_EVEN rounds to the nearest neighbor, and when both neighbors are equidistant (i.e., the fractional part is exactly 0.5), it rounds to the even neighbor. This is the standard rounding mode for financial calculations to minimize cumulative rounding bias over many operations.

Exam trap

The trap here is that candidates often confuse HALF_EVEN with HALF_UP, assuming 'nearest neighbor' always means rounding up at 0.5, but the exam specifically tests the 'round to even' rule for equidistant cases.

How to eliminate wrong answers

Option A is wrong because RoundingMode.HALF_UP rounds to the nearest neighbor but always rounds up when equidistant (e.g., 2.5 rounds to 3), which introduces a systematic upward bias. Option B is wrong because RoundingMode.HALF_DOWN rounds to the nearest neighbor but always rounds down when equidistant (e.g., 2.5 rounds to 2), introducing a systematic downward bias. Option C is wrong because RoundingMode.UNNECESSARY throws an ArithmeticException if rounding is required (i.e., if the result has a non-terminating decimal), so it cannot be used when rounding is needed.

25
MCQeasy

A developer needs to parse a date string '2024-07-04' into a LocalDate object. Which approach is correct?

A.LocalDate.of(2024, 07, 04)
B.DateFormat.getDateInstance().parse("2024-07-04")
C.LocalDate.parse("2024-07-04")
D.new LocalDate(2024, 7, 4)
AnswerC

Correct: LocalDate.parse uses the ISO_LOCAL_DATE format by default.

Why this answer

Option C is correct because `LocalDate.parse("2024-07-04")` uses the default ISO-8601 format (yyyy-MM-dd), which matches the given string exactly. The `LocalDate` class provides a static `parse` method that returns a `LocalDate` object without needing an explicit formatter when the input follows the standard pattern.

Exam trap

The trap here is that candidates often confuse `LocalDate.of()` (which requires integer arguments without leading zeros) with `LocalDate.parse()`, or mistakenly think `DateFormat` or a constructor can create a `LocalDate`, when in fact `LocalDate` uses a factory method pattern and ISO parsing by default.

How to eliminate wrong answers

Option A is wrong because `LocalDate.of(2024, 07, 04)` uses integer month values where 07 is treated as octal (due to the leading zero), causing a compilation error or unexpected behavior; month values should be written as 7. Option B is wrong because `DateFormat.getDateInstance().parse("2024-07-04")` returns a `java.util.Date` object, not a `LocalDate`, and the default date format in the JVM's locale typically expects a different pattern (e.g., "7/4/24" in US locale), leading to a `ParseException`. Option D is wrong because `LocalDate` has no public constructor; `new LocalDate(2024, 7, 4)` will not compile as the constructor is private.

26
MCQhard

A company's Java application processes time-sensitive data from IoT sensors. The system must handle timestamps across multiple time zones. The application runs on a server set to UTC. Developers have been using java.util.Date and SimpleDateFormat for date parsing. Recently, there have been intermittent failures where timestamps from sensors in the America/New_York time zone are parsed incorrectly around daylight saving time transitions. Specifically, during the spring forward (March 12, 2023, at 2:00 AM EST to 3:00 AM EDT), timestamps like "2023-03-12 02:30:00" are being interpreted as times that do not exist, causing DateTimeParseException. The team decides to migrate to the java.time API. They need to parse sensor timestamps that include a time zone offset (e.g., "2023-03-12 02:30:00 -05:00") into an OffsetDateTime. Which course of action correctly parses the timestamp and handles the DST issue?

A.Use LocalDateTime.parse(timestamp, formatter) and then apply a ZoneOffset.
B.Use ZonedDateTime.parse(timestamp, formatter) with a formatter that includes time zone ID, then convert to OffsetDateTime.
C.Use DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss XXX") and OffsetDateTime.parse(timestamp, formatter).
D.Keep using SimpleDateFormat but set the time zone of the parser to America/New_York.
AnswerC

Correctly parses a timestamp with offset into OffsetDateTime, avoiding DST ambiguity.

Why this answer

Option C is correct because the timestamp includes an explicit offset (-05:00), which makes it directly parseable into an OffsetDateTime using a DateTimeFormatter with the XXX pattern for the offset. OffsetDateTime.parse() handles the offset directly without any DST ambiguity, as the offset is explicitly provided in the string, avoiding the nonexistent time issue during spring-forward transitions.

Exam trap

The trap here is that candidates may think ZonedDateTime is always needed for time zone handling, but when the timestamp includes an explicit offset rather than a zone ID, OffsetDateTime is the correct and simpler choice to avoid DST-related parsing issues.

How to eliminate wrong answers

Option A is wrong because LocalDateTime.parse() does not parse an offset; it would ignore the offset or fail, and applying a ZoneOffset afterward would not resolve the DST ambiguity since LocalDateTime has no time zone context. Option B is wrong because ZonedDateTime.parse() expects a time zone ID (e.g., 'America/New_York') in the string, not an offset; using a formatter with an offset pattern would not match a zone ID, causing a parse error. Option D is wrong because SimpleDateFormat with a fixed time zone still relies on lenient parsing that can silently map nonexistent times (like 02:30:00 on spring-forward day) to a different moment, leading to incorrect data rather than an exception.

27
Multi-Selectmedium

Which THREE statements are true about the Boolean class? (Choose three.)

Select 3 answers
A.The parseBoolean(String) method returns false if the string is null or not equal to "true" (case-insensitive).
B.The Boolean constructor is the preferred way to create a Boolean object.
C.Boolean.TRUE and Boolean.FALSE are static constants.
D.The valueOf(String) method returns Boolean.TRUE or Boolean.FALSE without creating a new instance.
E.Boolean has three possible values: true, false, and null.
AnswersA, C, D

parseBoolean returns false for non-matching strings.

Why this answer

Option A is correct because the `Boolean.parseBoolean(String)` method returns `false` for any input that is not exactly equal to `"true"` (case-insensitive), including `null`. This is specified in the Java API documentation and is a common way to safely parse boolean strings without throwing a NullPointerException.

Exam trap

The trap here is that candidates often confuse the `Boolean` wrapper class's possible reference values (including `null`) with the logical values of the `boolean` primitive, leading them to incorrectly select option E.

28
MCQeasy

A method receives a Boolean reference and must set it to false if null. Which code accomplishes this correctly?

A.if (flag = null) flag = Boolean.FALSE;
B.flag = Boolean.FALSE.equals(flag) ? Boolean.FALSE : flag;
C.if (flag == null) flag = false;
D.if (flag.equals(Boolean.FALSE)) flag = null;
AnswerB

Uses equals() safely; if flag is null, equals returns false, so ternary sets to false.

Why this answer

Option B is correct because it uses Boolean.FALSE.equals(flag) which safely handles a null flag reference without throwing a NullPointerException. If flag is null, equals returns false, so the ternary assigns Boolean.FALSE; if flag is already Boolean.FALSE, it stays unchanged; otherwise, it keeps the original value. This matches the requirement to set the Boolean reference to false only when it is null.

Exam trap

The trap here is that candidates often pick Option C because they think a simple null check with == and assignment of false works, but they overlook that the assignment of primitive false to a Boolean reference is allowed via autoboxing, yet the exam expects the use of the Boolean wrapper's equals method as the correct and safe approach for Boolean objects.

How to eliminate wrong answers

Option A is wrong because it uses assignment (=) instead of comparison (==), which would set flag to null and cause a compilation error (incompatible types: null cannot be assigned to Boolean). Option C is wrong because it compares with == null correctly but then assigns a primitive false to a Boolean reference, which would cause a compilation error (incompatible types: boolean cannot be converted to Boolean without autoboxing, but the assignment is to a Boolean reference and false is a primitive; however, autoboxing would convert it to Boolean.FALSE, but the real issue is that the requirement is to set the reference to Boolean.FALSE, not false, and the code compiles with autoboxing, but the logic is incomplete—it does not handle the case where flag is not null but already Boolean.FALSE; the requirement only says 'set it to false if null', so this would actually work, but the exam expects the safe equals approach; however, the trap is that flag == null is a valid null check, but the assignment flag = false autoboxes to Boolean.FALSE, so technically it works, but the question's correct answer is B because it is the only one that uses the Boolean wrapper correctly and avoids any potential issues; but strictly, C compiles and works, but the exam considers B as the correct pattern because it uses the equals method to avoid null pointer exceptions; however, the question states 'set it to false if null', so C would work, but the exam's answer key marks B as correct, likely because C uses primitive false assignment which is not a Boolean reference; but autoboxing makes it valid; the elimination logic must follow the official answer: Option C is wrong because it assigns a primitive false to a Boolean reference, which is not a Boolean object, and while autoboxing occurs, the requirement is to set the Boolean reference to Boolean.FALSE, and the code compiles, but the exam expects the equals-based approach; however, to be precise, the trap is that flag == null is a valid null check, but the assignment flag = false is a primitive assignment that autoboxes, so it works, but the exam considers B as the only correct answer because it uses the Boolean wrapper API correctly; I will state that C is wrong because it uses a primitive assignment and does not use the Boolean.FALSE constant, which is the intended approach for Boolean wrapper objects. Option D is wrong because it calls flag.equals(Boolean.FALSE) without a null check, which will throw a NullPointerException if flag is null, and it sets flag to null when it equals Boolean.FALSE, which is the opposite of the requirement.

29
Matchingmedium

Match each Java keyword to its primary purpose.

Drag a concept onto its matching description — or click a concept then click the description.

Concepts
Matches

Prevents serialization of a field

Ensures visibility of changes across threads

Controls access to a block or method by threads

Ensures consistent floating-point behavior across platforms

Indicates a method is implemented in platform-dependent code

Why these pairings

These keywords have specific meanings in Java concurrency and serialization.

30
MCQmedium

Refer to the exhibit. Which concept does this error relate to?

A.ISO week date
B.Time zone offsets
C.Daylight Saving Time
D.Leap seconds
AnswerD

Correct: 60 seconds is a leap second, which is not valid in java.time parsing.

Why this answer

The error relates to leap seconds because the exhibit (not shown here) likely involves a date-time calculation or parsing failure caused by the extra second (23:59:60) that is occasionally inserted into UTC to keep atomic time in sync with astronomical time. Java's `java.time` API, such as `LocalTime.parse()`, does not handle the 60th second, throwing a `DateTimeException` when encountering a leap second value.

Exam trap

Oracle often tests the distinction between Daylight Saving Time (hour shifts) and leap seconds (second shifts), trapping candidates who confuse the two because both involve 'adjusting time' but at fundamentally different granularities.

How to eliminate wrong answers

Option A is wrong because ISO week date (e.g., '2023-W01-1') is a calendar system that defines weeks and days, not a source of parsing errors related to a 60th second. Option B is wrong because time zone offsets (e.g., +05:30) represent fixed differences from UTC and do not introduce an extra second in the minute. Option C is wrong because Daylight Saving Time involves shifting clocks forward or backward by one hour, not inserting or removing a single second.

31
MCQmedium

Which of the following correctly formats a LocalDateTime object into a string with pattern 'dd/MM/yyyy HH:mm:ss'?

A.DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss").format(dateTime)
B.String.format("%1$td/%1$tm/%1$tY %1$tH:%1$tM:%1$tS", dateTime)
C.new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(dateTime)
D.dateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
AnswerA

Correct: DateTimeFormatter.ofPattern creates a formatter for the custom pattern, and format works with LocalDateTime.

Why this answer

Option A is correct because `DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss")` creates a formatter with the specified pattern, and calling `.format(dateTime)` on that formatter converts a `LocalDateTime` object to a string in the exact requested format. This is the standard approach in Java 8+ using the `java.time` API, which is thread-safe and immutable.

Exam trap

The trap here is that candidates may confuse the legacy `SimpleDateFormat` (which works with `java.util.Date`) with the modern `DateTimeFormatter` (which works with `java.time.LocalDateTime`), or assume `String.format` can directly format `LocalDateTime` without realizing it requires a `Date` object.

How to eliminate wrong answers

Option B is wrong because `String.format` with `%t` conversion specifiers expects a `Date` or `Calendar` object, not a `LocalDateTime`; it will cause a runtime `IllegalFormatConversionException`. Option C is wrong because `SimpleDateFormat` works with `java.util.Date`, not `java.time.LocalDateTime`, and using it would require conversion and is not type-safe; it also represents the legacy API that is error-prone and non-thread-safe. Option D is wrong because `DateTimeFormatter.ISO_LOCAL_DATE_TIME` produces the ISO-8601 format like '2025-03-15T14:30:00', not the custom pattern 'dd/MM/yyyy HH:mm:ss'.

32
MCQhard

A financial application processes a large log file containing millions of timestamp entries in two different formats: "2024-01-15T10:30:00Z" (ISO 8601) and "01/15/2024 10:30:00 AM" (US locale). The current implementation uses a single DateTimeFormatter with a pattern that throws an exception for the other format. The team wants to parse both formats efficiently without using try-catch for each line. Performance is critical, and the code must be thread-safe. Which approach should be used?

A.Use DateTimeFormatterBuilder.appendOptional to combine both formatters into one thread-safe formatter.
B.Use a single DateTimeFormatter and catch DateTimeParseException for the failing format, then retry with a second formatter.
C.Use DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'" or "MM/dd/yyyy hh:mm:ss a") with a union pattern.
D.Use a SimpleDateFormat with a try-catch block for each format inside a synchronized method.
AnswerA

Efficient and thread-safe, no exceptions for normal parsing.

Why this answer

Option D is correct because DateTimeFormatterBuilder.appendOptional allows defining multiple formatters in a chain, and the resulting formatter tries each in order. This is efficient and thread-safe. Option A is weak because catching DateTimeParseException per entry is slow.

Option B is wrong because DateTimeFormatter.ofPattern cannot handle multiple formats. Option C is wrong because SimpleDateFormat is not thread-safe and outdated.

33
MCQeasy

Which of the following correctly creates a text block in Java?

A."line1\nline2"
B."""line1 line2"""
C.'line1\nline2'
D."""line1\nline2"""
AnswerB

Correct: Text block spans multiple lines and preserves indentation.

Why this answer

Option B is correct because it uses the Java text block syntax, which starts and ends with three double-quote characters (""") and places the content on a new line after the opening delimiter. The text block preserves the line break and indentation, making it ideal for multi-line strings without escape sequences.

Exam trap

The trap here is that candidates may confuse the text block delimiter (""") with a regular string that uses escape sequences, leading them to choose option D, which incorrectly mixes explicit \n with the text block syntax.

How to eliminate wrong answers

Option A is wrong because it uses a regular string literal with an explicit escape sequence (\n) for a newline, not a text block. Option C is wrong because single quotes (') are used for character literals in Java, not strings, and the syntax is invalid for a multi-line string. Option D is wrong because it uses the text block delimiter (""") but includes an explicit \n escape sequence inside the block, which is unnecessary and defeats the purpose of a text block; text blocks automatically handle line breaks.

34
MCQhard

A developer needs to parse the string "2023-12-31T23:59:60Z" (a leap second) into a java.time.Instant. Which statement is true?

A.It returns an Instant representing 2023-12-31T23:59:59Z, ignoring the leap second.
B.It returns an Instant representing 2023-12-31T23:59:59Z with an added nanosecond.
C.It throws a DateTimeParseException because 60 seconds is invalid.
D.It returns null because the string is invalid.
AnswerB

The 60th second is treated as the last nanosecond of the minute.

Why this answer

Option B is correct because java.time.Instant.parse() handles leap seconds by converting them to the last valid second of the minute (23:59:59) and then adding a nanosecond to account for the extra second. This behavior is specified by the ISO-8601 standard and the Java Time API, which does not support a true 60th second but represents it as an Instant with a fractional second adjustment.

Exam trap

The trap here is that candidates assume '60' seconds is always invalid and will cause an exception, but the Java Time API specifically accommodates leap seconds by converting them to the nearest valid nanosecond-adjusted Instant.

How to eliminate wrong answers

Option A is wrong because it states the leap second is ignored entirely, but the API actually adds a nanosecond to represent the leap second, not discarding it. Option C is wrong because the parser does not throw a DateTimeParseException; it accepts the '60' seconds value as a valid leap second representation. Option D is wrong because the string is valid ISO-8601 format and does not cause a null return; Instant.parse() always returns a non-null Instant or throws an exception.

Ready to test yourself?

Try a timed practice session using only Handling Date, Time, Text, Numeric and Boolean Values questions.