0

What is the purpose of the expression "new String(...)" in Java?

In short the problem is to create a substring from a huge string so the author argues that it is better to use the new String(substring) constructor because string returned by substring() will use the same char[] as parent string, so if we do not use new String() then the huge literal will still be in use. in order to avoid unnecessary huge char[] occupying memory it is better to create new String object with smaller char[] and hence shorter literal. the huge char[] can then be garbage collected But! as I learned literal are never garbage collected!

Garbage collection of String literals

So even though huge char[] is not pointed by any local variable it can still stay in the literal pool hence defeats the purpose of efficiently using memory.

Community
  • 1
  • 1
noobCoder
  • 292
  • 2
  • 17
  • 4
    That is outdated. `substring` no longer shares underlying arrays (unless it was a no-op). – Savior Apr 15 '16 at 16:24
  • See [Use of the String(String) constructor in Java](http://stackoverflow.com/questions/465627/use-of-the-stringstring-constructor-in-java). – Savior Apr 15 '16 at 16:25
  • And http://stackoverflow.com/questions/13803505/why-string-class-has-copy-constructor?lq=1 – Savior Apr 15 '16 at 16:26
  • ok! I learned as of java 7 created new char[] for substring. but then it totally eliminates need of new String() constructor, doesn't it? – noobCoder Apr 15 '16 at 16:27
  • String literals in java can be GCed if the classloader which loaded the class which defined these literals is GCed. – TheLostMind Apr 15 '16 at 16:27
  • This question (if we consider it a question, as there are only statements) seems to assume that `substring` is always invoked an a literal. Just consider that you could invoke `substring` on a `String` instance that is *not* a literal, so the behavior of literals is not relevant then. Yes, starting with jdk7u6, this constructor becomes (even) less relevant, but existing constructors can’t be removed at will. Maybe [this answer](http://stackoverflow.com/a/40726930/2711488) helps… – Holger Nov 21 '16 at 19:02

0 Answers0