About Question enthuware.ocpjp.v17.2.3577
Posted: Fri Sep 23, 2022 3:36 am
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.
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.