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.