3

If I get a string object from a method call or from StringBuilder.toString(), does this string gets added to the String pool?

Does String get added to the pool only during class load?

Sufiyan Ghori
  • 18,164
  • 14
  • 82
  • 110
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
  • http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#intern() – Jeroen Vannevel Jan 12 '15 at 14:04
  • 1
    possible duplicate of [Java String Pool](http://stackoverflow.com/questions/2486191/java-string-pool) – Joe Jan 12 '15 at 14:06
  • @Joe No, I wanted to know if Strings can be added in String pool during run time as well by calling methods which return string, and if intern is the ONLY way to get the string added to String pool. This is something other questions in SO has not covered decisively as they have only covered an obvious scenario of literal vs new String(). – gurvinder372 Jan 12 '15 at 14:33

2 Answers2

8

I get a string object from a method call or from StringBuilder.toString(), does this string gets added to the String pool?

StringBuilder.toString() --> (creates and ) returns a String which is on the heap (not on the String constants pool).

if you do return "hi" in your method, then the String constant pool's hi's reference will be returned.

Strings can be added to the String constants pool during runtime by calling intern() on them.

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
5

you can call intern() on a String object. This will put the String object in the pool if it is not already there, and return the reference to the pooled string. (If it was already in the pool, it just returns a reference to the object that was already there).

Sufiyan Ghori
  • 18,164
  • 14
  • 82
  • 110
abdotalaat
  • 735
  • 7
  • 10