What is the output of the following application?
package mypkg;//from w w w. ja v a 2 s . c om import java.util.function.*; public class Main { private int layer; public Main(int layer) { super(); this.layer = layer; } public static void open(UnaryOperator<Main> task, Main main) { while((main = task.accept(main)) != null) { System.out.print("X"); } } public static void main(String[] wood) { open(s -> { if(s.layer<=0) return null; else return new Main(s.layer--); }, new Main(5)); } }
C.
The code does not compile, so Option A is incorrect.
The lambda expression compiles without issue, making Option B incorrect.
The task variable is of type UnaryOperator<Main>, with the abstract method apply()
.
There is no accept()
method defined on that interface, therefore the code does not compile, and Option C is the correct answer.
If the code was corrected to use the apply()
method, the rest of it would compile without issue.
At runtime, it would then produce an infinite loop.
On each iteration of the loop, a new Main instance would be created with 5, since the post- decrement (--) operator returns the original value of the variable, and that would make Option D the correct answer.