About Question enthuware.ocpjp.v17.2.3577

All the posts and topics that contain only an error report will be moved here after the error is corrected. This is to ensure that when users view a question in ETS Viewer, the "Discuss" button will not indicate the presence of a discussion that adds no value to the question.

Moderators: Site Manager, fjwalraven

Post Reply
theujior
Posts: 11
Joined: Fri Sep 09, 2022 8:41 am
Contact:

About Question enthuware.ocpjp.v17.2.3577

Post by theujior »

the question explains
1. replace(char oldChar, char newChar) method returns the same String object if both the parameters are same, i.e. if there is no change.
Thus, "String" == "String".replace('g', 'g') will return true.


Why can't "String".replace('g', 'g') return new another "String" object?

API Document explains
If the character oldChar does not occur in the character sequence represented by this String object, then a reference to this String object is returned. Otherwise, a String object is returned that represents a character sequence identical to the character sequence represented by this String object, except that every occurrence of oldChar is replaced by an occurrence of newChar.

'g' occurs in "String".
It does not explain the case where oldChar is same with newChar, that is, the character sequence of result is same with the character sequence of this String.
I think that the result of "String" == "String".replace('g', 'g') depends on JVM.

And the question explains
2. replace(CharSequence oldSeq, CharSequence newSeq) method returns a new String object even if there is no change after replacement.
Thus, "String" == "String".replace("g", "g") will return false.


on Eclipse Adoptium JVM
"String" == "String".replace('g', 'g') return true.
"String" == "String".replace("g", "g") return true. replace(char,char) is called internally.
"String" == "String".replace("ng", "ng") return false.

I think that the result depends on JVM.

admin
Site Admin
Posts: 10384
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: About Question enthuware.ocpjp.v17.2.3577

Post by admin »

You are right. The JavaDoc does not clearly specify what happens when both the params are the same. But no, it doesn't depend on the JVM.
It depends on how the replace methods are coded.

The explanation is saying that if both the params are the same then the same reference is returned. Although this is true for replace(char , char), I agree that this fact should not be relied upon because it is not specified in the JavaDoc.

The explanation has been updated.

thank you for your feedback!

Post Reply

Who is online

Users browsing this forum: No registered users and 7 guests