nerdexam
Oracle

1Z0-819 · Question #90

Given: public class Main { public static void main(String[] args) { var numbers = List.of(1,2,3,4,5,6,7,8,9,10); OptionalInt integer = numbers.stream().filter(x -> x % 3 != 0).reduce((i, j) -> i)…

The correct answer is D. The variable result is not present, nothing is done. Option D is correct because result is never declared in this code - the variable holding the stream result is named integer, not result. Referencing an undeclared variable causes a compile-time error, so the program never runs at all; "nothing is done" means the code fails…

Working with Streams and Lambda Expressions

Question

Given: public class Main { public static void main(String[] args) { var numbers = List.of(1,2,3,4,5,6,7,8,9,10); OptionalInt integer = numbers.stream().filter(x -> x % 3 != 0).reduce((i, j) -> i); result.ifPresent(System.out::print); // line 1 } } Which is true about line 1?

Options

  • AIf the value is not present, a NoSuchElementException is thrown at run time.
  • BIf the value is not present, 0 is printed at run time.
  • CIf the value is not present, a NullPointerException is thrown at run time.
  • DThe variable result is not present, nothing is done.

How the community answered

(53 responses)
  • A
    6% (3)
  • B
    2% (1)
  • C
    9% (5)
  • D
    83% (44)

Explanation

Option D is correct because result is never declared in this code - the variable holding the stream result is named integer, not result. Referencing an undeclared variable causes a compile-time error, so the program never runs at all; "nothing is done" means the code fails before execution.

Why the distractors are wrong:

  • A is wrong because ifPresent never throws NoSuchElementException - that's what get() throws on an empty Optional. ifPresent simply does nothing when the value is absent.
  • B is wrong because ifPresent takes a Consumer and only acts if a value exists; it has no default fallback value like 0.
  • C is wrong because ifPresent performs a null-safe presence check internally - it cannot produce a NullPointerException through normal usage.

Memory tip: When you see Optional methods on an exam, remember the trio: get() = throws if empty (dangerous), orElse() = returns default if empty (safe), ifPresent() = silently skips if empty (safe). Any answer claiming ifPresent throws an exception or prints a default is wrong by definition. Also train your eye to match variable names across lines - a mismatched identifier is always a compile error, not a runtime behavior question.

Topics

#Stream.reduce()#Optional.ifPresent()#Stream filtering#Lambda expressions

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice