Jain Amit wrote:As per K&B7 the case constant must be a compile-time constant and only a final variable can be used. This implies s is not a compile time constant but s2 is.
Jain Amit wrote:But why "ann" (line 4) is a compile-time constant? I got this wrong but more than the correct answer I am interested in understanding this concept. I don't have behind the scene knowledge of Java.
Jain Amit wrote:I guess a String literal "ann" is still created in the heap but the reference is stored in the String pool. So, will the compiler create String object "ann" in heap in this case?
When a .java file is compiled into a .class file, any String literals are noted in a special way, just as all constants are. When a class is loaded (note that loading happens prior to initialization), the JVM goes through the code for the class and looks for String literals. When it finds one, it checks to see if an equivalent String is already referenced from the heap. If not, it creates a String instance on the heap and stores a reference to that object in the constant table. Once a reference is made to that String object, any references to that String literal throughout your program are simply replaced with the reference to the object referenced from the String Literal Pool.
Sorry if I'm out of context, a bit difficult to follow since I see references to book and other code snippets.Jain Amit wrote:I guess a String literal "ann" is still created in the heap but the reference is stored in the String pool. So, will the compiler create String object "ann" in heap in this case?
Jain Amit wrote:I am trying to figure out Java's behind the scene policies but it's tough for me right now.
nick woodward wrote:(i think) most methods on strings implicitly call 'new' too so the pool doesn't get checked either
Liutauras Vilda wrote:
Jain Amit wrote:1. "str" - is a string literal and compile time constant.
2. final String s1 = "bob"; s1 is a compile time constant.
Jain Amit wrote:3. String s2 = "bob"; s2 is NOT a compile time constant as it is not declared final.
4. final String s3; s3 is NOT a compile time constant since s3 is not initialised while declaring.
s3 = "bob";
Consider Paul's rocket mass heater. |