1Z0-819 · Question #81
Given: public class Main { public static void main(String[] args) { Consumer<String> msg -> System.out::print; // line 1 Consumer.accept("Hello Lambda !"); } } This code results in a compilation…
The correct answer is D. Consumer consumer = System.out::print. Option D is correct because System.out::print is a valid method reference whose signature - void print(String) - exactly matches Consumer's single abstract method void accept(T t), and it uses proper assignment syntax (Consumer consumer = ...;), fixing both errors on line 1…
Question
Options
- AConsumer consumer = msg -> {return System.out.print(msg);};
- BConsumer consumer = var arg -> System.out.print(arg);};
- CConsumer consumer = (String arg) -> System.out.print(args);
- DConsumer consumer = System.out::print;
How the community answered
(45 responses)- A18% (8)
- B4% (2)
- C7% (3)
- D71% (32)
Explanation
Option D is correct because System.out::print is a valid method reference whose signature - void print(String) - exactly matches Consumer's single abstract method void accept(T t), and it uses proper assignment syntax (Consumer consumer = ...;), fixing both errors on line 1 (missing = and invalid mixing of lambda and method-reference syntax).
Option A fails because return System.out.print(msg); is illegal - print() returns void, and Java does not allow return <void-expression>; inside a block body; the block should simply be { System.out.print(msg); } with no return.
Option B fails because using var as a lambda parameter type requires parentheses - (var arg) -> ... - and the stray } at the end is also a syntax error.
Option C fails semantically because it references args (the String[] from main's parameter) instead of the declared lambda parameter arg, so the consumer would never print the string passed to accept - it would always print the array reference instead.
Memory tip: When assigning a method to a Consumer, think "does this method take one argument and return nothing?" - if yes, a method reference (::) is always the shortest and cleanest assignment. Method references (::) and lambdas (->) are interchangeable forms, but you can never mix them in one expression.
Topics
Community Discussion
No community discussion yet for this question.