Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

question about strings

 
Jay Dilla
Ranch Hand
Posts: 201
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
had this question in a phone interview
i think i answered it right but not sure

anyway the question was if you have a string variable called name
and you put a value in it
then you put another value into it, what happens to the first value

so something like:



what happens to John?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the general case, it's simply no longer referenced by the variable, and may be eligible for garbage collection if nothing else references it. In the specific case you've shown, though, it's a String literal, which the JVM keeps in a special "String pool", so that it won't be collected. If the String was created in some other way, though, it might be.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is an interesting area. Strings are objects like any others. But strings that are also "constants" get special treatment. See Strings, Literally here on the ranch for details.
 
Jay Dilla
Ranch Hand
Posts: 201
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
O I said it's on the heap somewhere floating around and ready for System.gc() to grab it up. What is this thing about "String pool"? How would I have to write it in order for it to be eligible for garbage collection?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The String pool is a special collection of Strings which are defined in class files; the JVM uses it so such things can be shared and not duplicated.

A String literal -- a double-quoted String -- will always be stored in the String pool, and won't be collected (at least, in theory, until the class that defines it is collected.) There's no way to remove it from the pool.

Any other String -- one that comes from new String(), from BufferedReader.readLine(), etc, etc, -- will behave as you've described.

EXCEPT if you call intern() on it -- which will copy it into the String pool, and return that pooled copy.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic