1Z0-829 · Question #38
Given the content of the in. tart file: 23456789 and the code fragment: char[] buffer = new char[8]; int count = 0; try (FileReader in = new FileReader("in.txt"); FileWriter out = new…
The correct answer is D. 0123456789. There is an important inconsistency in this question worth flagging before explaining. Based on the code as written, the actual correct answer is C (0123456789234567), not D. Here is why: out.write(buffer) always writes all 8 characters of the buffer, regardless of how many…
Question
Options
- A01234567801234
- B012345678
- C0123456789234567
- D0123456789
- E012345678901234
How the community answered
(64 responses)- A17% (11)
- B9% (6)
- C2% (1)
- D69% (44)
- E3% (2)
Explanation
There is an important inconsistency in this question worth flagging before explaining.
Based on the code as written, the actual correct answer is C (0123456789234567), not D.
Here is why: out.write(buffer) always writes all 8 characters of the buffer, regardless of how many characters in.read(buffer) actually placed into it on that pass.
With 0123456789 (10 chars) and a buffer of size 8:
| Pass | count | Buffer contents | Written to out.txt |
|---|---|---|---|
| 1 | 8 | 01234567 | 01234567 |
| 2 | 2 | 89234567 (only positions 0-1 updated; 234567 is stale from pass 1) | 89234567 |
Result: 01234567 + 89234567 = 0123456789234567 → C
Why D is wrong: 0123456789 would only appear in out.txt if the code used out.write(buffer, 0, count) - the three-argument overload that limits the write to exactly count characters. The code as shown uses the single-argument form, which ignores count entirely.
Memory tip: The bug in this pattern is the mismatch between how many bytes were read (count) and how many bytes were written (always buffer.length). Whenever you see out.write(buffer) without count, ask: "what stale data lurks in the rest of that array?"
Recommendation: Double-check your source material - this question as written has the wrong answer key. If the official answer is D, the code in your source likely reads
out.write(buffer, 0, count), notout.write(buffer).
Topics
Community Discussion
No community discussion yet for this question.