Reputation: 3304
I have a String which is already initialized. Now I want to replace the contents with a character array. I would like to know if doing the following:
stringObj = new String(charArr);
is fine?
Would this lead to any memory leaks?
Sorry if this question has been answered already, I could not find the answer to this at all.
Upvotes: 0
Views: 90
Reputation: 524
String stringobj = "This is fine";
stringobj = new String(charArray);
Actually now stringobj will contain the reference of memory location containing new Char Array and the previous location will be taken care by the Garbage Collector.
Upvotes: 0
Reputation: 569
since string is immutable , eventually you will get new object it wont get replace with previous object . For this example there wont be memory leaks since this is only one string, but yes if your applicaiton is based on huge amount of string manipulation doing this way there will be memory leaks. You should use StringBuffer or String Builder.
Upvotes: 0
Reputation: 26175
It is important to understand that you have only changed the one reference to the String. If you have any other references they still point to the old String object. That would both prevent garbage collection and lead to continued use of the old value.
In particular, if you do this inside a method that was passed stringObj as an argument, the caller's references are unaffected by the assignment.
In other words stringObj is not an object. It is a pointer to an object. You are changing that one pointer so that it points to a new object.
Upvotes: 0
Reputation: 1874
Don't worry. the Garbage Collector is taking care of it! -> http://javarevisited.blogspot.co.at/2011/04/garbage-collection-in-java.html
Upvotes: 0
Reputation: 308733
Sure, it's fine. The reference refers to a new String. The old one is eligible for GC.
There are some considerations for intern and perm space, but there's no memory leak. This is how Java works.
Your code won't be harmed by such a construct. It's great to be mindful of best practices, but premature optimization without data is a losing game. Write your app to the best of your ability, profile it if performance is unacceptable, and fix the problems that contribute most to your performance issue. Don't try to imagine that you know where the problems will be.
Upvotes: 1