Difficulty: Easy
Correct Answer: app
Explanation:
Introduction / Context:
This Java snippet tests understanding of zero-based indexing with substring(begin, end), charAt, and String immutability during concatenation. You must carefully map indexes to characters and then append a single character to a short substring.
Given Data / Assumptions:
Concept / Approach:
Remember: indices are 0-based, and substring’s end index is exclusive. Also, charAt returns a single char that can be concatenated to form a new String. No mutation occurs to previous String objects, only new ones are created.
Step-by-Step Solution:
Index map for "newspaper": 0 n, 1 e, 2 w, 3 s, 4 p, 5 a, 6 p, 7 e, 8 r. a.substring(5, 7) → characters at 5 and 6 → "ap". char b = a.charAt(1) → from "ap", index 1 is 'p'. a = a + b → "ap" + 'p' → "app". System.out.println(a) prints "app".
Verification / Alternative check:
Confirm by quickly printing intermediate values: print the substring and its charAt(1) to verify "ap" and 'p' before concatenation.
Why Other Options Are Wrong:
"apa"/"apep"/"apea"/"appe" misread either the exclusive end index or the exact character chosen by charAt(1). Only "app" matches the precise flow.
Common Pitfalls:
Confusing inclusive vs. exclusive bounds; off-by-one errors; assuming substring mutates the original String.
Final Answer:
app
Discussion & Comments