1z0-829 Exam QuestionsBrowse all questions from this exam

1z0-829 Exam - Question 19


Given the code fragment:

What is the result?

Show Answer
Correct Answer: CD

The code initializes a string 'a' with the value 'Hello! Java'. The first call to a.indexOf('Java') returns 7 because 'Java' starts at index 7 in the string. The a.replace('Hello!', 'Welcome!') method does not change 'a' itself because strings are immutable in Java; it returns a new string, which is not assigned to any variable. Therefore, the next call to a.indexOf('Java') still returns 7. The StringBuilder 'b' is created with the contents of 'a', so b.indexOf('Java') also returns 7. Hence, the output is 777.

Discussion

8 comments
Sign in to comment
testostawsOption: D
Jan 25, 2024

Print 777. a.replace("Hello!", "Welcome!") doesn’t change a. It creates a new string which is not used. Therefore, a.indexOf("Java") will return the same index (7) both times. The same index will be returned by b.indexOf("Java") since b is created from a.

c6437d5Option: D
Mar 25, 2024

D tested correct

TojoseOption: D
Jan 11, 2024

the right answer id D. 777, because String is unmutable

meltedoliveOption: D
Jan 16, 2024

right options D.

supersquaxOption: D
Jan 25, 2024

Right one is D. As Tojose writes, Strings are immutable. When doing a.replace(), it returns a new string which in this case isnt saved anywhere, and so "a" remains the same.

Bharadwaj240796Option: D
Feb 12, 2024

Prints : 777, correct answer!

UtemanOption: D
May 17, 2024

D is the correct answer

xplorerpjOption: D
Jun 24, 2024

D is correct answer