I am confused about these two things. I need a help. Please clear my doubt, whether String Constant Pool and String pool both are same concept. I faced this question on interview. I have already read lot of sites and blogs but, my doubt is not cleared.Please clear my doubts.
Thanks in Advance.
Both are the same thing. String Constant Pool contains constant string objects. Constant can be defined as String object holds the value at compile time. For more refer JLS.
String s="abc";
String s1="def";
String s2=s+"def";
String s3="abc"+"def";
System.out.println(s2==s3); // print false
But if you make s as final then
final String s="abc";
String s1="def";
String s2=s+"def";
String s3="abc"+"def";
System.out.println(s2==s3); // print true
In above case s3 is a compile time constant as s is final .
The String pool (= "String constant pool"):
This is an informal nickname given to String's class-level/static intern storage. Note: javadoc mentions "pool of strings" http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#intern%28%29.
It's a set containing every unique String value interned during app execution. Interning happens automatically for all compile-time String constants (literals and fixed expressions) and also for all runtime String values where String.intern() is called. The JLS mandates that compile-time constant expressions of type String are always "interned" so as to share unique instances, using the method String.intern. http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.28
The JVM spec does not mandate any particular internal structure for objects. http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-2.html#jvms-2.7
The Java Language Spec does mandate that a String object has a constant (unchanging) value. http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.3.3
That means that a String variable can only change value by referencing a new String object with a new value - of course, this is internally managed by the compiler & JVM . That also means that all items in the pool are String constants.
The Constant Pool (not focused on Strings, but does include Strings):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With