简体   繁体   中英

How do I copy a replace an existing string with a character array in Java

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.

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.

Don't worry. the Garbage Collector is taking care of it! -> http://javarevisited.blogspot.co.at/2011/04/garbage-collection-in-java.html

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM