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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With