In Java, what is the exact output of this String-manipulation program? Ensure you trace substring indexes and character concatenation step-by-step.\n\nString a = 'newspaper';\na = a.substring(5, 7);\nchar b = a.charAt(1);\na = a + b;\nSystem.out.println(a);

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:

  • Original string is "newspaper".
  • The call substring(5, 7) includes index 5 and excludes index 7.
  • charAt(1) fetches the second character from that 2-character substring.
  • String concatenation a + b appends the character b to the end of a.


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

More Questions from Java.lang Class

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion