nerdexam
Oracle

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…

Using Java I/O API

Question

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 FileWriter("out.txt")) { while((count = in.read(buffer)) != -1) { out.write(buffer); } } What is the content of the out.txt file?

Options

  • A01234567801234
  • B012345678
  • C0123456789234567
  • D0123456789
  • E012345678901234

How the community answered

(64 responses)
  • A
    17% (11)
  • B
    9% (6)
  • C
    2% (1)
  • D
    69% (44)
  • E
    3% (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:

PasscountBuffer contentsWritten to out.txt
180123456701234567
2289234567 (only positions 0-1 updated; 234567 is stale from pass 1)89234567

Result: 01234567 + 89234567 = 0123456789234567C

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), not out.write(buffer).

Topics

#FileReader/FileWriter#Buffer management#I/O operations#Character arrays

Community Discussion

No community discussion yet for this question.

Full 1Z0-829 Practice