I'm a little confused on what does string pool actually contain.
When we say String s = "abc"
, does this mean that during compile time, the string object is put in the string pool or is it the reference that is put?
I'm a little confused on what does string pool actually contain.
When we say String s = "abc"
, does this mean that during compile time, the string object is put in the string pool or is it the reference that is put?
The statement String s = "abc"
causes the abc
to be created in String constant pool if it is not already present. If it is present, then a reference will be returned . You can find a good tutorial about string constant pool here.
http://www.thejavageek.com/2013/06/19/the-string-constant-pool/
Each time you create a String that way, the JVM checks whether this Object is in the String constant pool. If so, a reference to the "pooled" instance will be returned. If it doesn't, a new instance initialized and put in the pool:
----------- String s = "Hello";
|
٧
+-------------------+
| "Hello" |
+-------------------+
pool
String pool is just a cache for string literal.Whenever we assign string literal to string reference ,literal will be searched in string pool and it will be assigned to reference variable.
In String s="abc"
JVM will search literal "abc"
in string pool and will be assign reference of it to reference variable s
.
____________
refers | |
String s ------->| abc |<---- String Pool
|___________|
The pool you are talking about is in the heap and all the references that exist are present on stack(not heap). When you create a string String s = "abc";
String literal "abc" is placed in the String pool and all further references will point to this literal except the case in which you create a String object using new(separate memory space is allocated on the heap in this case).
The string pool refers to a place in memory where Strings are defined. The string pool has references to constants to be reused. The string pool is what allows this to happen:
String a = "a" + "b";
String b = "ab";
if(a == b) {
System.out.println("this will print");
}
a==b will evaluate to true, because the compiler sees both String a and String b as equal to "ab" so this string is stored in the String pool and both String a and String b point to this one reference.
"abc" is defined at compile time here and hence would be automatically interned. This string object will hence go to string intern pool. If one already exists there, its reference would be returned.The string intern pool is a part of main java heap since Java 7(and we know heaps are to contain objects).