Use method references with Streams.
1. The correct answer is B.
Runnable r = Question_11_1::print;
It's equivalent to:
Runnable r = () -> Question_11_1.print();
And equivalent to:
Runnable r = new Runnable() {
public void run() {
Question_11_1.print();
}
}
The print()
method returns another Runnable
instance, but as this is not saved or executed, nothing is done.
2. The correct answer is A.
Consumer c = Question_11_2::print;
It's equivalent to:
Consumer c = (Question_11_2 q) -> q.print();
And equivalent to:
Consumer c = new Consumer() {
public void accept(Question_11_2 q) {
q.print();
}
}
That when executed, it just prints "Hi"
.
3. The correct answers are A and C.
Option A is true. You can have a method reference of a constructor.
Option B is false. Method references only replace one-method lambda expressions.
Option C is true. When using method references, you don't have to specify the arguments the method receives.
Option D is false. The ::
operator is just used in method references.
4. The correct answer is D.
Option A and B are not valid method references.
Option C would be right if the method drive(int)
were static
, but because it's an instance method, option D is the right one.
5. The correct answer is B.
Runnable r = Question_11_5::new;
It's equivalent to:
Runnable r = () -> new Question_11_5();
And equivalent to:
Runnable r = new Runnable() {
public void run() {
new Question_11_5();
}
}
However, r.run()
is never executed, so nothing is printed.
6. The correct answer is D.
Compilation fails because
BiFunction<String, String, Test> f = Test::new;
It's equivalent to:
BiFunction<String, String, Test> f =
(String s1, String s2) -> new Test(s1, s2);
And class Test
only has constructors that take zero and one arguments.
7. The correct answers are A and D.
Option A is correct because the private constructor can be used inside the main
method.
Option B is wrong because with an UnaryOperator
, a parameter of type Question_11_7
is expected.
Option C is wrong because with a Consumer
a parameter of type Question_11_7
is expected, and nothing is returned.
Option D is correct because a Supplier
returns an instance of Question_11_7
by calling the static
method create()
.