why string constant pool in java
Answers were Sorted based on User's Feedback
Answer / loknathreddy
String constant pool is a separate block of memory where
String object are held by JVM.
If a String object is created directly by using assignment
operator(=) as
String s1="Hello";
then it is stored in String Constant pool.
One of important characteristic of String constant pool is
that it doesn’t create same String object if there is
already in the String constant pool.
String s1 = “Hello”;
String s2 = “Hello”;
For above two String objects, JVM creates only one object
in the String constant pool and for the second string
reference variable (s2) will created, it points the string
object which is created for s1. In this case, (s1 == s2) is
true.
but when we use new operator to create object then this
object will store in heap memory.. be carefull on this.
| Is This Answer Correct ? | 26 Yes | 2 No |
Answer / shabina
To make Java more memory efficient, the JVM set aside a special area of memory called as "String Constant Pool" or "String Literal Pool".
When the compiler encounters a string literal, it checks the pool to see if an identical strong already exists or not, If not then it creates a new string literal object.
A String object is created out of the string constant pool, even if an equal already exists in the pool. Considering all that avoid new string unless you specially know that you need it.
JVM has a string pool where it keeps at most one object of any string. String literals always refers to an object in the string literal pool.
String objects created with the new string do not refer to objects in the string pool but can be made to using string's intern() method.
the java.lang.string.intern() returns an intended string, that is one that has an entry in the global string pool, then it will be added.
there is a table always maintaining a single reference to each unique object int the string literal pool ever created by an instance of the runtime in order to optimize space.
That means that they always have a reference to string objects in string literal pool. Therefore, the string objects in the string literal pool are not eligible for garbage collection.
| Is This Answer Correct ? | 1 Yes | 0 No |
What is a java string?
What does the exclamation mark mean in java?
What is the difference between Java1.4 and Java1.5
How garbage collection is done in java?
What is the purpose of object oriented programming?
What is the difference between pageContext and page implicit objects in jsp?
9 Answers Gspann Technologies, Merrill Lynch, Polaris,
How many types of equations are there?
Write a program to reverse array in place?
What are the different tags provided in jstl?
What is the parse method in java?
Say any two properties in beans?
Why inputstreamreader is used in java?