1Z0-819 · Question #87
Given: 1. public class Secret { 2. String[] names; 3. public Secret(String[] names) { 4. this.names = names; 5. } 6. public String[] getNames() { 7. return names; 8. } 9. } Which three actions…
The correct answer is E. Change line 2 to private final String[] names. The listed answer of only E appears incomplete - this "Choose three" question has three correct answers: B, D, and E. Why B, D, and E are correct: Java SE secure coding guidelines require defensive copying of mutable objects at trust boundaries. Making the field private final…
Question
- public class Secret {
- String[] names;
- public Secret(String[] names) {
- this.names = names;
- }
- public String[] getNames() {
- return names;
- }
- } Which three actions implement Java SE security guidelines? (Choose three.)
Options
- AChange line 7 to return new String[].
- BChange line 4 to this.names = names.clone();
- CChange the getNames() method name to getNames().
- DChange line 7 to return Arrays.copyOf(names, names.length).
- EChange line 2 to private final String[] names.
- FChange line 7 to return Arrays.asList(names).
- GChange line 2 to protected volatile String[] names..
How the community answered
(29 responses)- A3% (1)
- B3% (1)
- E83% (24)
- G10% (3)
Explanation
The listed answer of only E appears incomplete - this "Choose three" question has three correct answers: B, D, and E.
Why B, D, and E are correct: Java SE secure coding guidelines require defensive copying of mutable objects at trust boundaries. Making the field private final (E) enforces encapsulation and prevents external reassignment of the reference. Cloning the input array in the constructor (B) ensures a caller can't retain a reference to the internal array and mutate it after construction. Returning a copy in getNames() via Arrays.copyOf (D) prevents callers from receiving a direct reference to the internal state and changing it - all three together fully protect the mutable array.
Why the distractors are wrong:
- A (
return new String[]) returns an empty array, breaking functionality rather than securing it. - C renames
getNames()togetNames()- identical, so no change at all. - F (
Arrays.asList(names)) returns aListbacked by the original array, so callers can still mutate the underlying data viaset(). - G (
protected volatile) makes the field less restricted (protected is broader than private) andvolatileaddresses thread visibility, not object encapsulation.
Memory tip: Think "copy in, copy out, lock it down" - clone on the way in (constructor), copy on the way out (getter), and use private final to lock the reference. Any option that skips one of these three steps leaves a security gap.
Topics
Community Discussion
No community discussion yet for this question.