javastringreplacejava-13

Java difference in String.replace between java 12 and 13


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.


Solution

  • 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.