Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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?

like image 551
nitrobuster Avatar asked Jan 13 '14 18:01

nitrobuster


1 Answers

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.

like image 73
Sergey Kalinichenko Avatar answered Sep 16 '22 12:09

Sergey Kalinichenko