1Z0-819 · Question #153
Given: import java.util.*; public class Main { static Map<String, String> map = new HashMap<>(); static List<String> keys = new ArrayList<>(List.of("A", "B", "C", "D")); static String[] values =…
The correct answer is D. Map: 4 Keys: 0 Values: 0. Before responding, let me check if any skill applies here. This is a Java exam explanation task - no specific skill covers this. Proceeding directly. --- There's an error in the stated correct answer. The actual output of this program is A: Map: 0 Keys: 0 Values: 0, not D…
Question
Options
- AMap: 0 Keys: 0 Values: 0
- BThe compilation fails.
- CMap: 4 Keys: 4 Values: 4
- DMap: 4 Keys: 0 Values: 0
- EMap: 4 Keys: 0 Values: 4
How the community answered
(58 responses)- A2% (1)
- B9% (5)
- C2% (1)
- D83% (48)
- E5% (3)
Explanation
Before responding, let me check if any skill applies here.
This is a Java exam explanation task - no specific skill covers this. Proceeding directly.
There's an error in the stated correct answer. The actual output of this program is A: Map: 0 Keys: 0 Values: 0, not D.
Here's why: The { } block inside the class (without the static keyword) is an instance initializer, not a static initializer. It only executes when new Main() is called to create an instance - but main() is a static method that never creates any instance. So the loop that populates map never runs, leaving map empty (size 0). Then keys.clear() empties the list and values = new String[0] replaces the array with an empty one, yielding sizes of 0 for all three.
D would be correct only if the block were declared static { ... }, which would run at class-loading time and populate the map before main() clears keys and replaces values. That scenario gives Map: 4, Keys: 0, Values: 0.
Why the other options are wrong as written:
- B (compile fails) - code is syntactically valid Java.
- C (Map: 4 Keys: 4 Values: 4) - ignores
keys.clear()and thevaluesreassignment. - E (Map: 4 Keys: 0 Values: 4) -
values = new String[0]replaces the reference with an empty array, sovalues.lengthis 0, not 4.
Memory tip: static { } = class-level, runs once at load time. { } alone = instance-level, runs per new. If no instance is created, a bare { } block is dead code.
Bottom line: As the code is written, the answer is A. If your source lists D, the question likely contains a typo - the
statickeyword was dropped from the initializer block.
Topics
Community Discussion
No community discussion yet for this question.