Question 9
Back to Exercise
What is the output of the following Java program?
class Order {
private final StringBuilder items = new StringBuilder();
private double total;
Order add(String item, double price) {
if (!items.isEmpty()) items.append(", ");
items.append(item);
total += price;
return this; // returning the same object allows chaining
}
@Override public String toString() { return "[" + items + "] Rs " + total; }
}
public class Main {
public static void main(String[] args) {
Order o = new Order().add("Pen", 20).add("Book", 120).add("Bag", 899.5);
System.out.println(o);
}
}
- A [Pen, Book, Bag] Rs 1039.5 Correct
- B [Bag] Rs 899.5
- C [Pen] Rs 20.0
- D Compilation error
Correct Answer: Option A
Each add returns this, so the next call works on the same Order (a fluent interface).
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!