Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Constant Pool vs String pool

Tags:

java

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.

like image 868
JDGuide Avatar asked Feb 14 '26 08:02

JDGuide


2 Answers

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 .

like image 93
amicngh Avatar answered Feb 16 '26 21:02

amicngh


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):

  • Exists within each class file (and in memory, for each class loaded). Is a per-class record of the constants (i.e. final variables) in use. http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.4 http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-2.html#jvms-2.5.5
like image 23
Glen Best Avatar answered Feb 16 '26 20:02

Glen Best



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!