1Z0-809 · Question #227
Given the code fragments: ``java public class Product { String name; Integer price; Product(String name, Integer price) { this.name = name; this.price = price; } public void printVal() {…
The correct answer is A. TV Price :110 Refrigerator Price :2100. Option A is correct because the Consumer<Product> raise lambda mutates each product's price in-place by calling setPrice(getPrice() + 100) - making TV 1100 and Refrigerator 2100 - and since forEach(raise) executes before forEach(Product::printVal), the updated prices are what…
Question
public class Product {
String name;
Integer price;
Product(String name, Integer price) {
this.name = name;
this.price = price;
}
public void printVal() { System.out.print(name + " Price:" + price + " "); }
public void setPrice(int price) { this.price = price; }
public Integer getPrice() { return price; }
}
and
List<Product> li = Arrays.asList(new Product("TV", 1000), new Product("Refrigerator", 2000));
Consumer<Product> raise = e -> e.setPrice(e.getPrice() + 100);
li.forEach(raise);
li.forEach(Product::printVal);
What is the result?Options
- ATV Price :110 Refrigerator Price :2100
- BA compilation error occurs.
- CTV Price :1000 Refrigerator Price :2000
- DThe program prints nothing.
How the community answered
(23 responses)- A78% (18)
- B4% (1)
- C9% (2)
- D9% (2)
Explanation
Option A is correct because the Consumer<Product> raise lambda mutates each product's price in-place by calling setPrice(getPrice() + 100) - making TV 1100 and Refrigerator 2100 - and since forEach(raise) executes before forEach(Product::printVal), the updated prices are what get printed. (Note: "TV Price:110" in option A appears to be a typo for "TV Price:1100.")
Why the distractors are wrong:
- B (compilation error): The code is valid -
Consumer<Product>is a proper functional interface,Arrays.asList(...)returns aList<Product>, andProduct::printValis a legal instance method reference. - C (original prices): This would be correct only if
forEach(raise)were never called, but it is called first, so prices are already updated whenprintValruns. - D (prints nothing):
printValexplicitly callsSystem.out.print(...), so output is always produced.
Memory tip: Think of Consumer<T> as a "side-effect machine" - it takes an object and changes it without returning anything. When you see forEach(consumer) followed by forEach(printer), the first pass mutates, the second pass reads the mutated state.
Community Discussion
No community discussion yet for this question.