您的位置:首页 > 其它

The String Constant Pool

2016-04-15 10:27 423 查看
In the previous post, we have learned about string immutability. Another interesting thing about strings in java is The String Constant Pool. So what is it exactly? It is a special place where the collection of references
to string objects are placed. What makes this so special? we will try to understand it now.

In our tutorial about String immutability, we have learned that string literals cannot be modified and multiple reference variable can refer to the same string literal. Let us first write a program to understand object comparison and references

123456789public class StringConstantPool { public static void main(String[] args) { String s = "prasad"; String s2 = "prasad";  System.out.println(s.equals(s2)); System.out.println(s == s2); }}
The output of the above code is

1

2

true

true

Now lets know what happens here step by step
The class is loaded when JVM is invoked.
JVM will look for all the string literals in the program
First, it finds the variable 
which refers to the  literal “
prasad

and it will be created in the memory
A reference for the literal “
prasad
” will be placed in the string constant pool memory.
Then it finds another variable 
s2 
which is referring to the same string literal “
prasad
“.
Now that JVM has already found a string literal “
prasad
“, both the variables 
and 
s2 
wil
refer to the same object i.e. “
prasad
“.

The diagram below demonstrates this





String literals referred

Now we have looked into the case when string literals are created without using the 
new 
operator. What happens if 
String s2 = new ("prasad"); 


As we are invoking the 
new
 keyword, The object “
prasad

will be created when the new String(“prasad”) is invoked. This is unlike the string literal “
prasad
” which is created when class is loaded.

Now the values of objects referenced by variable 
and variable 
s2 
are the same i.e.
“prasad” but those are not the same objects. They refer to different objects. We will verify this with a program

123456789public class StringConstantPool { public static void main(String[] args) { String s = "prasad"; String s2 = new String("prasad"); System.out.println(s.equals(s2)); System.out.println(s == s2);  }}
This outputs,

1

2

true

false

The contents of both objects are the same so 
equals 
method returns 
true

The objects referred by both variables are different so 
==
 operator returns 
false


This is elaborated in this diagram





String with new keyword

Points to be remembered
String literals with same values will always refer to the same String object
String objects created using new operator will be different from literals

Hope this helped clarify doubts regarding string literals.

from: http://www.thejavageek.com/2013/06/19/the-string-constant-pool/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  String constant pool