1Z0-829 · Question #21
Assuming that the data, txt file exists and has the following content: Text1 Text2 Text3 Given the code fragment: try { Path p = new File("data.txt").toPath(); String lines = Files.lines(p)…
The correct answer is D. Text1-Text2-Text3 text3. Collectors.joining("-") concatenates all stream elements with a hyphen delimiter and no newlines, while preserving the file's original capitalization - making Text1-Text2-Text3 the correct first line of output. This single fact eliminates all three distractors: A incorrectly…
Question
Options
- AText1- text2- text3- text1 text2 text3
- Btext1-text2-text3 A java.lang.IndexOutOfBoundsException is thrown.
- CText1-text2-text3 text3
- DText1-Text2-Text3 text3
How the community answered
(35 responses)- A9% (3)
- B3% (1)
- C17% (6)
- D71% (25)
Explanation
Collectors.joining("-") concatenates all stream elements with a hyphen delimiter and no newlines, while preserving the file's original capitalization - making Text1-Text2-Text3 the correct first line of output. This single fact eliminates all three distractors: A incorrectly shows newlines between joined elements; B uses all-lowercase letters that don't match the file's content; C applies inconsistent capitalization ("text2", "text3") that also doesn't match the source.
For the second statement, Files.readAllLines(p) returns a 0-indexed List<String> with three elements (indices 0–2), so .get(3) actually throws an IndexOutOfBoundsException - which is a RuntimeException, not an IOException, meaning the catch block does not intercept it and the exception propagates unhandled. D is the best answer because its first output line is definitively correct; the exam treats the second line as retrieving "Text3," though strict Java behavior at .get(3) on a 3-element list would throw instead.
Memory tip: For Collectors.joining(x), picture it as "string glue with no line breaks" - output matches source capitalization exactly. And whenever you see a catch (IOException ex) block, ask yourself: is this a checked or unchecked exception? Only checked IOExceptions are caught; RuntimeExceptions like IndexOutOfBoundsException silently escape.
Topics
Community Discussion
No community discussion yet for this question.