Hi java gurus, As explained in the 'awesome' K&B book (page 359): ".... JVM sets aside a special area of memory called the 'string constant pool'. When the compiler encounters a string literal, it checks the pool if an identical string exists....." I have two doubts: a) So in the following piece of code, is the "java" object is created in the pool twice?? As I understand, jvm creates this string in the pool then returns it's reference to 's'. but after line#2 executes, reference to "java" is lost ...so after line#3 whether compiler will create a new "java" in the pool and returns its reference or it will use the first one only? If it uses the first one then how it gets to it as after line#2, the reference is kinda lost in open space? <code> 1. String s = "java"; 2. String s = "language"; 3. String s1 = "java"; </code> b) Does the garbage collection also runs on this 'string constant pool' or what? Thanks, Deep
Each time the Java "interpreter" finds a string literal (like "java") it checks if a String object was already created in the string pool representing the same content. If it finds it, it does not create it again, but it return its reference. (*) Yes String objects created for string literals can be g.c.ed , but luckily, under certain conditions that are far beyond what is required for the SCJP exam.
(*) Not the whole truth: the compiler makes this process more much more efficent but it is an easy way to understand the string pool.
SCJP2. Please Indent your code using UBB Code
Joined: Dec 17, 2002
Thanks. However, I still have doubt reg Q#1: In the following code, how many String objects are created? As per your explanation, it should be two only. Please correct me if I'm wrong. code: 1. String s = "java"; 2. String s = "language"; 3. String s1 = "java";
Well, to make it less confusing, this code doesn't compile because s reference is defined twice Then, if we are to follow K&B, I don't see either nulling the references, or rereferencing, or islands of isolation here. As Jose said, there might be certain circumstances where the String literals would be gc, I just don't see it from the code.