Is a new string created every time replaceAll() is used on a String?

java

Solution

You noted correctly that `String` objects in Java are immutable. The only case when replacement, substring, etc. methods do not create a new object is when the replacement is a no-op. For example, if you ask to replace all `'x'` characters in a `"Hello, world!"` string, there would be no new `String` object created. Similarly, there would be no new object when you call `str.substring(0)`, because the entire string is returned. In all other cases, when the return value differs from the original, a new object is created.

Problem

So I do know that java Strings are immutable. There are a bunch of methods that replace characters in a string in java. So every time these methods are called, would it involve creation of a brand new String, therefore increasing the space complexity, or would replacement be done in the original String itself. I'm a little confused on this concept as to whether each of these replace statements in my code would be generating new Strings each time, and thus consuming more memory?

Original source