1

I noticed a difference in the behaviour of the String.replace(CharSequence, CharSequence) between java 12 and 13.

java 12 and earlier:

System.out.println("String"=="String".replace("g","g")); //false

java 13 and later:

System.out.println("String"=="String".replace("g","g")); //true

Found that this is probably due to:

Optimize String.replace(CharSequence, CharSequence) for common cases

Is this unexpected behaviour?

Yes, I'm aware of the equals method.

  • You have an extra double quote in there. – Dave Doknjas Jul 05 '20 at 22:32
  • I suggest you read https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java/513839#513839 -- you shouldn't compare strings with `==` but use the `equals` method. – john16384 Jul 05 '20 at 22:33
  • Welcome TitaniumDave. My recommendation to the other #moderators: this question is valid and only should be considered "virtually duplicate" iff you are a java expert and know the answer. Therefore, this question should be opened, and the answer should point to the related answer. There may be other answers in the future in context of the OP well beyond the individual `equals` method. – Kind Contributor Jul 06 '20 at 12:22
  • A good summary of what has changed in `String.replace` in Java 9-13: https://stackoverflow.com/a/58199878/706317 – ZhekaKozlov Jul 06 '20 at 13:54
  • Thank you @ZhekaKozlov for providing more context. – TitaniumDave Jul 07 '20 at 11:43
  • @Todd Thank you. Glad you understood the question to a further extend. – TitaniumDave Jul 07 '20 at 11:43

1 Answers1

5

The API specification makes no guarantees of whether String.replace returns a new String object or if it reuses the original when possible. The result of the comparison is "unspecified". That means it may change from one version to the next, just like you've discovered.

Use the .equals method to compare strings for equality.

Joni
  • 108,737
  • 14
  • 143
  • 193