Hi All ! Could anybody help me understand the pooling mechanism of Strings in Java. The documentation says, that String class internally does this pooling, but I cud not find anything in the String class code that gives a hint to that.
Vibhor Mittal<br /> <br />The Harder U Work, The Luckier U Get !!
The pooling is not done at runtime by the String class, but at compile time by the compiler.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Joined: Jun 03, 2003
Can you please explain it a little bit more? how does compiler manages that? And why does documentation says that String class itself pools all the Strings? What about the Strings that are created at runtime? I suppose they are also pooled somewhere. If not where are they kept? I would deeply appreciate if some one can give some detailed explanation. thanX in advance..
Ilja's not telling you the whole story. There are multiple levels of pooling or sharing that go on. What Ilja's alluding to is the fact that Strings that appear as constants in .class files are shared, so that "abc" == "abc" is true; a single instance will be used for both double-quoted String literals. But there's another way to get at this same pooling mechanism. By default, runtime Strings are not shared, but if you want them to be, then you can use the String.intern() method. This method looks in that same internal table, and if the String appears in the table, it returns the copy from the table; otherwise it adds the String to the table and returns it. This means, for example that
Hi. ThanX for your reply - Hill. Yes Thomas, I am actually interested in the actual implementation of the pooling. i.e. how it is implemented in code. Even I found this method as a native method. So I cud not understand what is happening under the hood :-/
Hi, I am a new user to Java Rench. hello to all. Just read the explaination for the String pooling. I am a bit apprihensive about the answer that pooling is done at the compile time...My question is... What all happens at the compile time... because pooling can be done for objects..does that mean that objects are created at the compile time..?? ( my understanding say..that a kind of memory map is created at the compile time ) actual memory allocation happens at the run time only..Is it a right assumption to make?. Am i clear about the question?
author and iconoclast
The phrase "pooling at compile time" means that multiple identical literal strings in a class are turned into one single constant pool entry (data in the .class file). At runtime, this entry is put into the intern() pool, which implies that all indentical constant strings across all classes will be shared.