Java SE 17 (1Z0-829) study materials
Java SE 17 (1Z0-829) study resources

Java SE 17 (1Z0-829) practice questions

One question at a time. Build your Java SE 17 (1Z0-829) understanding.

First 50 of 200 questions. Each one lists the choices, the correct answer, and an explanation. The checker at the top of this page saves progress in this browser when it is available.

Continue in the practice tool above to load more questions, 50 at a time.

Question 1Handling date, time, text, numeric and boolean values

Which class would you use to parse the string "2024-03-15" into a date without a time zone, using the ISO_LOCAL_DATE format by default?

  1. java.time.Instant
  2. java.time.ZonedDateTime
  3. java.time.OffsetTime
  4. java.time.LocalDate Correct answer.

Explanation

LocalDate.parse(CharSequence) uses DateTimeFormatter.ISO_LOCAL_DATE, which expects yyyy-MM-dd, so it directly parses "2024-03-15". LocalDate models a date without time or zone, which matches the input.

Question 2Handling date, time, text, numeric and boolean values

What is the result of evaluating LocalDate.of(2024, 2, 29).plusYears(1)?

  1. An exception is thrown
  2. 2025-02-29
  3. 2025-02-28 Correct answer.
  4. 2025-03-01

Explanation

2024 is a leap year, so 29 February exists. Adding one year gives an invalid date in 2025, and the java.time API adjusts to the last valid day of the month, producing 2025-02-28.

Question 3Handling date, time, text, numeric and boolean values

Which statement about java.time.LocalTime is true?

  1. It stores a time together with a zone offset
  2. It stores a time in UTC only
  3. It stores a time as epoch seconds
  4. It stores a time-of-day without a date or zone Correct answer.

Explanation

LocalTime represents a wall-clock time such as 13:45:30.123 with nanosecond precision, with no date and no time zone. OffsetTime adds an offset, and Instant represents epoch seconds.

Question 4Handling date, time, text, numeric and boolean values

Which class represents a duration measured in date-based units such as years, months and days?

  1. java.time.Period Correct answer.
  2. java.time.Instant
  3. java.time.Duration
  4. java.time.temporal.ChronoUnit

Explanation

Period models an amount of time in date units (years, months, days) and is used with LocalDate. Duration models time-based units such as seconds and nanos.

Question 5Handling date, time, text, numeric and boolean values

Which method converts a LocalDate into a LocalDateTime at the start of that day?

  1. atStartOfDay() Correct answer.
  2. toLocalDateTime()
  3. with(LocalTime.MIDNIGHT)
  4. atTime(0, 0)

Explanation

LocalDate.atStartOfDay() returns a LocalDateTime at 00:00 for that date. The overload atStartOfDay(ZoneId) returns a ZonedDateTime, handling daylight-saving gaps.

Question 6Handling date, time, text, numeric and boolean values

What does the following print? var d = LocalDate.of(2024, 1, 31); System.out.println(d.plusMonths(1));

  1. An exception is thrown
  2. 2024-03-02
  3. 2024-02-29 Correct answer.
  4. 2024-02-28

Explanation

2024 is a leap year, so February has 29 days. Adding one month to 31 January clamps the day to the last valid day of February, giving 2024-02-29.

Question 7Handling date, time, text, numeric and boolean values

Given DateTimeFormatter f = DateTimeFormatter.ofPattern("dd-MM-yyyy"); which call correctly parses "15-03-2024"?

  1. f.parse("15-03-2024")
  2. LocalDate.of("15-03-2024", f)
  3. LocalDate.format("15-03-2024", f)
  4. LocalDate.parse("15-03-2024", f) Correct answer.

Explanation

LocalDate.parse(CharSequence, DateTimeFormatter) applies the given pattern and returns a LocalDate. The pattern letters must match the input layout exactly.

Question 8Handling date, time, text, numeric and boolean values

What is printed by the following? var t = LocalTime.of(23, 30); System.out.println(t.plusHours(2));

  1. 01:30 Correct answer.
  2. 01:30 with the next day implied
  3. An exception is thrown
  4. 23:30

Explanation

LocalTime wraps around midnight; adding two hours to 23:30 gives 01:30. Because LocalTime holds no date, the day rollover is simply discarded.

Question 9Handling date, time, text, numeric and boolean values

Which statement about java.time.format.DateTimeFormatter is correct?

  1. It requires a Locale to be supplied
  2. It is immutable and thread-safe Correct answer.
  3. It is mutable and must be synchronized
  4. It can only format, not parse

Explanation

DateTimeFormatter instances are immutable and therefore thread-safe, unlike the legacy SimpleDateFormat. They can be shared freely between threads and used for both formatting and parsing.

Question 10Handling date, time, text, numeric and boolean values

Which expression yields a Duration representing 90 minutes?

  1. ChronoUnit.MINUTES.between(0, 90)
  2. Duration.ofMinutes(90) Correct answer.
  3. Duration.ofDays(90)
  4. Period.ofMinutes(90)

Explanation

Duration.ofMinutes(long) creates a time-based amount of 90 minutes, internally stored as 5400 seconds. Duration is the correct type for minute-level amounts.

Question 11Handling date, time, text, numeric and boolean values

What does LocalDate.of(2024, 3, 15).getDayOfWeek() return?

  1. 5
  2. THURSDAY
  3. SATURDAY
  4. FRIDAY Correct answer.

Explanation

15 March 2024 falls on a Friday, and getDayOfWeek() returns the DayOfWeek enum constant FRIDAY. The method returns an enum, not an int.

Question 12Handling date, time, text, numeric and boolean values

Which type would you use to represent a meeting time that must retain the time zone and adjust to daylight-saving changes?

  1. java.time.LocalTime
  2. java.time.LocalDateTime
  3. java.time.ZonedDateTime Correct answer.
  4. java.time.YearMonth

Explanation

ZonedDateTime combines a LocalDateTime with a ZoneId, so it carries full zone rules and reflects daylight-saving transitions. That makes it the correct choice for a zone-aware meeting time.

Question 13Handling date, time, text, numeric and boolean values

What is the result of the following? var date = LocalDate.of(2024, 3, 31); var zdt = date.atStartOfDay(ZoneId.of("Europe/London")); System.out.println(zdt);

  1. An exception is thrown
  2. 2024-03-31T00:00+01:00[Europe/London]
  3. 2024-03-31T01:00+01:00[Europe/London] Correct answer.
  4. 2024-03-31T00:00Z[Europe/London]

Explanation

On 31 March 2024 the UK clocks moved forward at 01:00, so midnight did not exist locally. atStartOfDay(ZoneId) resolves the gap to the first valid instant, 01:00 with offset +01:00.

Question 14Handling date, time, text, numeric and boolean values

Which statement about DateTimeFormatter.ofPattern("yyyy-MM-dd") and DateTimeFormatter.ISO_LOCAL_DATE is correct?

  1. Both produce the same output for a LocalDate, but the pattern-based formatter uses the default locale for text fields Correct answer.
  2. The pattern-based formatter is thread-safe while ISO_LOCAL_DATE is not
  3. ISO_LOCAL_DATE cannot format a LocalDate
  4. ISO_LOCAL_DATE requires an explicit Locale argument

Explanation

For numeric fields such as yyyy, MM and dd the outputs coincide, but a custom pattern formatter resolves text fields and locale-sensitive symbols using the default locale unless one is supplied. ISO_LOCAL_DATE is a fixed, locale-independent formatter.

Question 15Handling date, time, text, numeric and boolean values

What is printed by the following? var p = Period.of(0, 1, 40); var d = LocalDate.of(2024, 1, 1).plus(p); System.out.println(d);

  1. 2024-02-11
  2. 2024-01-41
  3. 2024-03-11
  4. 2024-02-10 Correct answer.

Explanation

Period stores years, months and days separately without normalization. Adding one month to 1 January gives 1 February, then adding 40 days lands on 10 February 2024.

Question 16Handling date, time, text, numeric and boolean values

Which call correctly formats a LocalDate using French month names regardless of the JVM default locale?

  1. DateTimeFormatter.ofPattern("d MMMM yyyy")
  2. Locale.setDefault(Locale.FRENCH)
  3. DateTimeFormatter.ofPattern("d MMMM yyyy", Locale.FRENCH) Correct answer.
  4. DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG)

Explanation

Passing Locale.FRENCH to ofPattern makes text fields such as MMMM resolve to French names without depending on the JVM default. This keeps the behaviour deterministic across environments.

Question 17Handling date, time, text, numeric and boolean values

Which expression converts the string "2024-03-15T10:15:30Z" into an Instant?

  1. ZonedDateTime.parse("2024-03-15T10:15:30Z")
  2. LocalDate.parse("2024-03-15T10:15:30Z")
  3. Instant.parse("2024-03-15T10:15:30Z") Correct answer.
  4. LocalDateTime.parse("2024-03-15T10:15:30Z")

Explanation

Instant.parse expects the ISO instant format ending in Z, which denotes UTC. The input matches that format exactly, so it parses directly into an Instant.

Question 18Handling date, time, text, numeric and boolean values

Which statement about Instant is correct?

  1. It stores only whole seconds
  2. It represents a point on the UTC timeline with nanosecond precision Correct answer.
  3. It cannot be converted to a ZonedDateTime
  4. It stores a local date and time without a zone

Explanation

Instant is a machine-readable timestamp measured from the epoch 1970-01-01T00:00:00Z, with nanosecond precision. It is always expressed against UTC.

Question 19Handling date, time, text, numeric and boolean values

What is the output of the following? var d = LocalDate.of(2024, 6, 15); System.out.println(d.with(TemporalAdjusters.firstDayOfNextMonth()));

  1. 2024-06-01
  2. 2024-07-01 Correct answer.
  3. 2024-06-30
  4. 2024-07-15

Explanation

TemporalAdjusters.firstDayOfNextMonth() moves to the first day of the following month. From 15 June 2024 that is 1 July 2024.

Question 20Handling date, time, text, numeric and boolean values

Which class would you use to represent only a month and a year, such as a credit card expiry of 03/2027?

  1. java.time.YearMonth Correct answer.
  2. java.time.LocalDate
  3. java.time.Year
  4. java.time.MonthDay

Explanation

YearMonth models a year and month combination and parses the format yyyy-MM by default. It is exactly suited to values such as card expiry dates.

Question 21Handling date, time, text, numeric and boolean values

What does the following print? var p1 = Period.ofDays(30); var p2 = Period.ofMonths(1); System.out.println(p1.equals(p2));

  1. An exception is thrown
  2. It does not compile
  3. true
  4. false Correct answer.

Explanation

Period equality compares the stored years, months and days fields, not the total elapsed time. Period.ofDays(30) has days=30 while Period.ofMonths(1) has months=1, so equals returns false.

Question 22Handling date, time, text, numeric and boolean values

Which method returns the number of days between two LocalDate values?

  1. ChronoUnit.DAYS.between(start, end) Correct answer.
  2. start.until(end).getDays()
  3. Duration.between(start, end).toDays()
  4. Period.between(start, end).getDays()

Explanation

ChronoUnit.DAYS.between(Temporal, Temporal) returns the total number of whole days between two dates as a long. This gives the total count rather than the residual day component.

Question 23Handling date, time, text, numeric and boolean values

Which statement about LocalDate, LocalTime and LocalDateTime is correct?

  1. They are interfaces implemented by mutable classes
  2. All three are mutable and modify the receiver in place
  3. Only LocalDate is immutable
  4. All three are immutable, so arithmetic methods return new instances Correct answer.

Explanation

The java.time value classes are immutable and final; methods such as plusDays return a new object and leave the receiver unchanged. This immutability makes them thread-safe.

Question 24Handling date, time, text, numeric and boolean values

What is the result of the following? var f = DateTimeFormatter.ofPattern("HH:mm"); var t = LocalTime.of(9, 5); System.out.println(t.format(f));

  1. An exception is thrown
  2. 09:5
  3. 9:05
  4. 09:05 Correct answer.

Explanation

The pattern HH uses a two-digit 24-hour field and mm uses a two-digit minute field, so both are zero-padded. The output is therefore 09:05.

Question 25Handling date, time, text, numeric and boolean values

Which expression correctly obtains the current date-time in a specific zone using the system clock, with the zone ID and offset retained in the result?

  1. LocalDateTime.now(ZoneId.of("Asia/Tokyo"))
  2. Instant.now(ZoneId.of("Asia/Tokyo"))
  3. ZoneId.now("Asia/Tokyo")
  4. ZonedDateTime.now(ZoneId.of("Asia/Tokyo")) Correct answer.

Explanation

ZonedDateTime.now(ZoneId) reads the system clock and returns the current date-time with the given zone and its rules. The result carries both the offset and the zone id.

Question 26Handling date, time, text, numeric and boolean values

Which class from java.time represents a date and time without any time zone or offset, such as 2024-05-20T14:30?

  1. ZonedDateTime
  2. Instant
  3. OffsetDateTime
  4. LocalDateTime Correct answer.

Explanation

LocalDateTime holds a date and a time but deliberately carries no zone or offset information, so it is the correct type for a zone-less date-time value. ZonedDateTime and OffsetDateTime both attach zone or offset data, and Instant represents a point on the UTC timeline.

Question 27Handling date, time, text, numeric and boolean values

What is printed by the following? var d = LocalDate.of(2024, 2, 29); System.out.println(d.plusYears(1));

  1. An exception is thrown
  2. 2025-03-01
  3. 2025-02-29
  4. 2025-02-28 Correct answer.

Explanation

Adding one year to 29 February 2024 would produce an invalid date because 2025 is not a leap year. The java.time API resolves this by returning the last valid day of the month, so the result is 2025-02-28.

Question 28Handling date, time, text, numeric and boolean values

Which statement about java.time.Duration is correct?

  1. It models an amount of time in seconds and nanoseconds and is suitable for time-based values such as hours and minutes. Correct answer.
  2. It models an amount of time in years, months and days and is suitable for date-based values.
  3. It always requires a ZoneId to be created.
  4. It can be used with LocalDate but not with LocalTime.

Explanation

Duration stores a quantity of time as seconds plus a nanosecond adjustment, which makes it appropriate for machine-scale time such as hours, minutes and seconds. It is not date-based and does not require a zone.

Question 29Handling date, time, text, numeric and boolean values

What is the result of the following? var d = LocalDate.of(2024, 3, 10); var p = Period.ofWeeks(3); System.out.println(d.plus(p));

  1. 2024-03-31 Correct answer.
  2. 2024-03-24
  3. 2024-03-17
  4. 2024-04-01

Explanation

Period.ofWeeks(3) is stored internally as 21 days, and adding 21 days to 10 March 2024 gives 31 March 2024. The calculation is straightforward because no month boundary is crossed.

Question 30Handling date, time, text, numeric and boolean values

Which expression correctly parses the text "2024-06-30" into a LocalDate using only built-in ISO handling?

  1. LocalDate.parse("2024-06-30") Correct answer.
  2. new LocalDate("2024-06-30")
  3. LocalDate.parse("2024-06-30", DateTimeFormatter.ofPattern("yyyy-MM-dd"))
  4. LocalDate.of("2024-06-30")

Explanation

LocalDate.parse(CharSequence) uses DateTimeFormatter.ISO_LOCAL_DATE by default, which accepts the yyyy-MM-dd form, so the single-argument call succeeds. The other calls either use a non-existent constructor or a factory method with an incompatible signature.

Question 31Handling date, time, text, numeric and boolean values

What does the following print? var f = DateTimeFormatter.ofPattern("yyyy-MM-dd"); var d = LocalDate.of(2024, 7, 4); System.out.println(f.format(d));

  1. 2024-07-04 Correct answer.
  2. 04-07-2024
  3. An exception is thrown
  4. 2024-7-4

Explanation

The pattern uses two pattern letters for month and day, which requests zero-padded two-digit output, so July becomes 07 and the fourth becomes 04. The year is printed with four digits, giving 2024-07-04.

Question 32Handling date, time, text, numeric and boolean values

Given a ZonedDateTime zdt for the zone America/New_York on 3 November 2024, which statement about its behavior during the daylight-saving fall-back overlap is correct?

  1. The later offset is always chosen automatically and cannot be changed.
  2. The earlier offset is used when the local time is ambiguous, and the later offset can be obtained with withLaterOffsetAtOverlap(). Correct answer.
  3. The zone rules are ignored and the offset remains fixed at UTC-04:00.
  4. An exception is thrown because the local time is ambiguous.

Explanation

During the fall-back overlap, a local time such as 01:30 occurs twice. ZonedDateTime resolves the ambiguity by selecting the earlier offset, and withLaterOffsetAtOverlap() returns an equivalent value using the later offset.

Question 33Handling date, time, text, numeric and boolean values

What is printed by the following? var d = LocalDate.of(2024, 1, 15); var t = LocalTime.of(9, 30); var ldt = LocalDateTime.of(d, t); System.out.println(ldt);

  1. 2024-01-15T09:30:00
  2. 2024-01-15 09:30
  3. 2024-01-15T09:30 Correct answer.
  4. 09:30T2024-01-15

Explanation

The default toString of LocalDateTime outputs the date, then the letter T, then the time, omitting seconds when they are zero. With a zero second value the output is 2024-01-15T09:30.

Question 34Handling date, time, text, numeric and boolean values

Which statement about java.time.Instant is correct?

  1. It represents a point on the UTC timeline and can be converted to a ZonedDateTime using atZone(ZoneId). Correct answer.
  2. It represents a local date and time without any offset.
  3. It stores a date but not a time.
  4. It can be formatted directly with DateTimeFormatter.ofPattern without a zone.

Explanation

Instant models an instantaneous point measured from the epoch in UTC and provides atZone to attach a zone and obtain a ZonedDateTime. It does not represent a local date-time and has no direct date-only form.

Question 35Handling date, time, text, numeric and boolean values

What is the result of the following? var d = LocalDate.of(2024, 5, 1); var z = ZoneId.of("America/Los_Angeles"); var zdt = d.atStartOfDay(z); System.out.println(zdt.toLocalDate());

  1. 2024-05-02
  2. An exception is thrown
  3. 2024-04-30
  4. 2024-05-01 Correct answer.

Explanation

atStartOfDay(ZoneId) returns the earliest valid time on that date in the given zone, which is still 1 May 2024 in Los Angeles. Converting back with toLocalDate therefore returns the same date.

Question 36Handling date, time, text, numeric and boolean values

Which expression produces a LocalDate representing the last day of the month for a given LocalDate d?

  1. d.minus(1, ChronoUnit.MONTHS)
  2. d.plus(TemporalAdjusters.lastDayOfMonth())
  3. d.with(TemporalAdjusters.lastDayOfMonth()) Correct answer.
  4. d.with(ChronoField.DAY_OF_MONTH, 31)

Explanation

TemporalAdjusters.lastDayOfMonth() is an adjuster designed for use with with, returning a date set to the final valid day of the current month. It handles short months and leap years correctly.

Question 37Handling date, time, text, numeric and boolean values

What is printed by the following? var d = LocalDate.of(2024, 8, 15); var f = DateTimeFormatter.ofPattern("EEEE, MMMM d"); System.out.println(f.format(d));

  1. Thursday, Aug 15
  2. Thu, August 15
  3. Thursday, August 15 Correct answer.
  4. Thursday, August 15, 2024

Explanation

Four pattern letters E request the full day-of-week name, four M request the full month name, and a single d requests the day-of-month without padding. The output is therefore Thursday, August 15.

Question 38Handling date, time, text, numeric and boolean values

Which statement about java.time.YearMonth is correct?

  1. It represents a year and a month, such as 2027-03, and can be created with YearMonth.of(2027, 3). Correct answer.
  2. It cannot be formatted with DateTimeFormatter.
  3. It represents a full date including the day of the month.
  4. It represents a duration of months rather than a specific month.

Explanation

YearMonth models a specific year and month without a day, which suits values such as card expiry dates. It supports formatting through DateTimeFormatter and is created with the of factory method.

Question 39Handling date, time, text, numeric and boolean values

What is the result of the following? var p = Period.of(1, 2, 3); var d = LocalDate.of(2024, 11, 30); System.out.println(d.plus(p));

  1. 2026-03-02
  2. 2026-01-31
  3. 2026-02-02 Correct answer.
  4. 2026-02-03

Explanation

Period addition applies years first, then months, then days. Adding one year and two months to 30 November 2024 gives 30 January 2026, then adding three days gives 2 February 2026.

Question 40Handling date, time, text, numeric and boolean values

Which statement about ChronoUnit between two LocalDate values is correct?

  1. ChronoUnit.DAYS.between(start, end) always returns a positive value regardless of order.
  2. ChronoUnit.DAYS.between(start, end) returns a Period object rather than a long.
  3. ChronoUnit.DAYS.between(start, end) throws an exception if end is before start.
  4. ChronoUnit.DAYS.between(start, end) returns the number of whole days from start to end, which is negative if end is before start. Correct answer.

Explanation

ChronoUnit.DAYS.between computes the signed difference in whole days between two temporal values. If the end is earlier than the start, the result is negative; no exception is thrown.

Question 41Utilizing collections and streams

Which interface in the Java Collections Framework guarantees that no duplicate elements are stored and does not define any ordering of its elements?

  1. java.util.Queue
  2. java.util.Set Correct answer.
  3. java.util.List
  4. java.util.Deque

Explanation

Set is the collection contract that forbids duplicate elements; its general contract says nothing about iteration order, which is added by subtypes such as SortedSet or LinkedHashSet. List and Queue allow duplicates, and Deque is a double-ended queue that also permits duplicates.

Question 42Utilizing collections and streams

Which statement about the Map hierarchy is correct?

  1. Map extends Iterable so it can be used directly in a for-each loop
  2. Map extends Collection and therefore inherits the add and iterator methods
  3. Map is not a subtype of Collection and stores key-value associations Correct answer.
  4. Map is a subtype of Set because its keys form a set

Explanation

Map is a separate root interface in java.util and does not extend Collection or Iterable, so a Map cannot be used directly in a for-each loop. Keys are unique, but the key set view is obtained through keySet() rather than inheritance.

Question 43Utilizing collections and streams

Given `var list = new ArrayList<>(List.of("a", "b", "c"));` followed by `list.set(1, "x");`, what is the result?

  1. The list contains [a, x, c] and the call succeeds Correct answer.
  2. An UnsupportedOperationException is thrown because List.of is immutable
  3. A compile-time error occurs because set cannot be applied to ArrayList
  4. The list contains [a, b, c] because set returns a new list

Explanation

The ArrayList constructor copies the elements of the immutable List.of result into a new, mutable ArrayList, so set works on the copy and replaces index 1. The immutability of the source list is irrelevant once the elements are copied.

Question 44Utilizing collections and streams

Which method should be used to remove elements from a collection while iterating with a for-each loop, avoiding a ConcurrentModificationException?

  1. Collection.removeIf called after the loop finishes
  2. Iterator.remove on the iterator obtained explicitly Correct answer.
  3. Collection.remove on the underlying collection
  4. List.remove(int) inside the loop

Explanation

The for-each loop hides the iterator, so structural modification through the collection triggers a fail-fast ConcurrentModificationException. Calling remove on the explicit Iterator updates both the collection and the iterator's expected modification count, which is the supported way to delete during iteration.

Question 45Utilizing collections and streams

What does the following print? `var s = new TreeSet<>(Comparator.reverseOrder()); s.add("b"); s.add("a"); s.add("c"); System.out.println(s);`

  1. An exception is thrown because the natural order conflicts with the comparator
  2. [b, a, c]
  3. [a, b, c]
  4. [c, b, a] Correct answer.

Explanation

TreeSet orders elements using the supplied comparator, and Comparator.reverseOrder() reverses the natural ordering of Comparable elements. The iteration order is therefore descending, giving [c, b, a]. No conflict arises because the comparator replaces natural ordering entirely.

Question 46Utilizing collections and streams

Which collection implementation should be chosen to preserve insertion order while still rejecting duplicate elements?

  1. HashSet
  2. TreeSet
  3. PriorityQueue
  4. LinkedHashSet Correct answer.

Explanation

LinkedHashSet maintains a doubly linked list over the hash table, so iteration follows insertion order while the Set contract still prevents duplicates. HashSet gives no order guarantee, and TreeSet orders by comparison rather than insertion.

Question 47Utilizing collections and streams

What is printed by `Stream.of("apple", "banana", "cherry").filter(s -> s.length() > 5).count()`?

  1. 3
  2. 0
  3. 1
  4. 2 Correct answer.

Explanation

The predicate keeps only strings whose length exceeds five: banana and cherry each have six characters, while apple has five and is filtered out. The terminal count operation therefore returns 2.

Question 48Utilizing collections and streams

Which statement about stream pipelines is correct?

  1. Every intermediate operation must be followed immediately by a terminal operation
  2. A stream can be reused after a terminal operation and will replay the same elements
  3. A stream created from a collection modifies that collection when filtered
  4. Intermediate operations are lazy and execute only when a terminal operation is invoked Correct answer.

Explanation

Intermediate operations such as filter and map only build up the pipeline description; traversal of the source occurs when a terminal operation such as collect or forEach is called. This laziness allows short-circuiting and fusion of operations.

Question 49Utilizing collections and streams

What is the result of `Stream.of(1, 2, 3, 4).map(n -> n * 2).filter(n -> n > 4).findFirst()`?

  1. Optional[8]
  2. Optional[6] Correct answer.
  3. Optional[4]
  4. An Optional.empty() value

Explanation

Mapping doubles each element to 2, 4, 6, 8, and filtering keeps values greater than four, so 6 and 8 remain. findFirst returns the first surviving element in encounter order, which is Optional[6].

Question 50Utilizing collections and streams

Which collector groups stream elements by the first character of each string into a Map<Character, List<String>>?

  1. Collectors.toMap(s -> s.charAt(0), s -> s)
  2. Collectors.joining(",")
  3. Collectors.groupingBy(s -> s.charAt(0)) Correct answer.
  4. Collectors.partitioningBy(s -> s.charAt(0))

Explanation

groupingBy takes a classifier function and produces a Map whose values are Lists of elements sharing the same key by default. Here the classifier returns a Character, so the result type is Map<Character, List<String>>.