Java Files.readAllLines Indexing Behavior
Assuming that the data.txt file exists and has the following content: text1 text2 text3 Given the code fragment: What is the result? - 
Community Votes
100% of anonymous learners picked answer B. Votes are pick records left by other test-takers — they are not the verified answer.
Community Insight
The core concept tested is zero-based list indexing in Java; the common trap is assuming 1-based indexing or miscounting the number of lines returned by readAllLines.
This question tests Java I/O API usage with Files.readAllLines, establishing that the method returns a List with zero-based indexing where valid indices are 0 to size-1.
Learners often select options implying out-of-bounds access (like index 3) because they mistakenly assume 1-based indexing or fail to realize that a file with 3 lines only has indices 0, 1, and 2.
Community Discussion (3 comments)
Comments & Corrections
No comments yet — spotted an error or have a note? Share it below.
Expert Analysis
Why the Answer Is Correct
The code usesFiles.readAllLines which returns a List<String>. Lists in Java use zero-based indexing. If the file contains three distinct lines ('text1', 'text2', 'text3'), the list size is 3. Valid indices are 0, 1, and 2. Accessing lines.get(0), lines.get(1), and lines.get(2) retrieves all three texts. The code likely concatenates them with hyphens, resulting in 'text1-text2-text3'. Option B represents this correct output.Why the Other Options Are Wrong
Options suggesting 'text1-' imply missing elements or incorrect joining logic. Options suggesting an exception or different text usually stem from accessing index 3, which would throw anIndexOutOfBoundsException since index 3 is out of bounds for a list of size 3. Any option not matching the exact concatenated string of the three lines is incorrect based on standard stream/list processing shown in typical exam fragments.Community Comment Notes
Community members consistently confirm that Java lists are zero-indexed. As user supersquax noted, "Java uses 0 indexing so we only have items 0... and 2." Another user SrinivasJasti clarified that "the first line... has an index of 0." These comments reinforce that understanding the 0-to-N-1 range is critical to avoiding runtime errors in this context.Exam Strategy
Always verify the size of collections returned by I/O methods like readAllLines. Remember that get(size()) will always throw an exception; the last valid index is size() - 1.
Frequently Asked Questions
Why does accessing index 3 cause an exception?
Because the list has 3 elements, valid indices are 0, 1, and 2. Index 3 is out of bounds.
Does readAllLines return 1-based indexing?
No, it returns a standard Java List which is strictly zero-based.