Question 12
Back to Exercise
What is the output of the following Java program?
import java.util.HashMap;
import java.util.Map;
final class Currency {
private static final Map<String, Currency> CACHE = new HashMap<>();
static int created = 0;
final String code;
private Currency(String code) { this.code = code; created++; }
static Currency of(String code) {
return CACHE.computeIfAbsent(code.toUpperCase(), Currency::new);
}
}
public class Main {
public static void main(String[] args) {
Currency a = Currency.of("inr"), b = Currency.of("INR"), c = Currency.of("usd");
System.out.println((a == b) + " " + (a == c) + " " + Currency.created);
}
}
- A true false 2 Correct
- B false false 3
- C true true 1
- D false false 2
Correct Answer: Option A
The factory returns the cached object for a code it has seen, so only two objects are ever constructed.
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!