Java String Immutability and indexOf Result
Given the code fragment: What is the result? - 
Community Votes
100% of anonymous learners picked answer D. Votes are pick records left by other test-takers — they are not the verified answer.
Community Insight
The common trap is assuming string modification methods change the variable in-place; the insight is that strings are immutable, so the original reference stays the same.
This question tests the immutable nature of Java Strings and how methods like replace() return new instances without modifying the original. The correct answer is D because the index of 'Java' remains unchanged at 7.
Learners often choose option E (71010) by incorrectly assuming the replacement changes the string content or shifts indices, failing to realize 'a' is untouched.
Community Discussion (8 comments)
Comments & Corrections
No comments yet — spotted an error or have a note? Share it below.
Expert Analysis
Why the Answer Is Correct
The correct answer is D (777) because Java Strings are immutable. Whena.replace("Hello!", "Welcome!") is called, it returns a new String object but does not modify the existing variable a. Since a still holds the original value "Hello! Java", a.indexOf("Java") correctly returns 7. Variable b is initialized with the original a, so b.indexOf("Java") also returns 7. Thus, the output is three 7s.Why the Other Options Are Wrong
Option A (888) and C (7107) assume some shifting or partial replacement occurred. Option B (8109) suggests a complete misinterpretation of indices. Option E (71010) is the most likely distractor, resulting from learners thinking the replacement changed the string structure or thatreplace modifies the source in place, leading to incorrect index calculations for subsequent operations.Community Comment Notes
The community overwhelmingly agrees on D, citing immutability as the key factor. As Tojose noted, "the right answer id D. 777, because String is unmutable". Another commenter confirmed, "Print 777. a.replace... doesn’t change a." This consensus highlights a fundamental Java concept frequently tested in certification exams.Exam Strategy
Always remember that String objects in Java are immutable. Methods like replace, substring, or concat do not change the original string but return a new one. If you don't assign the result back to a variable, the original remains unchanged.
Frequently Asked Questions
Does String.replace() modify the original string?
No, Strings are immutable. replace() returns a new string; the original variable remains unchanged unless reassigned.
Why does indexOf return 7 again?
Because the variable 'a' was never updated with the result of replace(), so it still points to the original string containing 'Java' at index 7.