what is a specialized memory area that is a collection of references to the objects of the class string?
Mohammed
Guys, does anyone know the answer?
get what is a specialized memory area that is a collection of references to the objects of the class string? from screen.
Guide to Java String Pool
Learn how the JVM optimizes the amount of memory allocated to String storage in the Java String Pool.
Guide to Java String Pool
Last modified: July 20, 2020
Written by: baeldung
Java+ Core Java
Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:
> CHECK OUT THE COURSE
1. Overview
The String object is the most used class in the Java language.
In this quick article, we'll explore the Java String Pool — the special memory region where Strings are stored by the JVM.
2. String Interning
Thanks to the immutability of Strings in Java, the JVM can optimize the amount of memory allocated for them by storing only one copy of each literal String in the pool. This process is called interning.
When we create a variable and assign a value to it, the JVM searches the pool for a String of equal value.
If found, the Java compiler will simply return a reference to its memory address, without allocating additional memory.If not found, it'll be added to the pool (interned) and its reference will be returned.
Let's write a small test to verify this:
String constantString1 = "Baeldung";
String constantString2 = "Baeldung";
assertThat(constantString1)
.isSameAs(constantString2);
3. Strings Allocated Using the Constructor
When we create a String via the new operator, the Java compiler will create a new object and store it in the heap space reserved for the JVM.
Every String created like this will point to a different memory region with its own address.
Let’s see how this is different from the previous case:
String constantString = "Baeldung";
String newString = new String("Baeldung");
assertThat(constantString).isNotSameAs(newString);
4. String Literal vs String Object
When we create a String object using the new() operator, it always creates a new object in heap memory. On the other hand, if we create an object using String literal syntax e.g. “Baeldung”, it may return an existing object from the String pool, if it already exists. Otherwise, it will create a new String object and put in the string pool for future re-use.At a high level, both are the String objects, but the main difference comes from the point that new() operator always creates a new String object. Also, when we create a String using literal – it is interned.
This will be much more clear when we compare two String objects created using String literal and the new operator:
String first = "Baeldung";
String second = "Baeldung";
System.out.println(first == second); // True
In this example, the String objects will have the same reference.
Next, let's create two different objects using new and check that they have different references:
String third = new String("Baeldung");
String fourth = new String("Baeldung");
System.out.println(third == fourth); // False
Similarly, when we compare a String literal with a String object created using new() operator using the == operator, it will return false:
String fifth = "Baeldung";
String sixth = new String("Baeldung");
System.out.println(fifth == sixth); // False
In general, we should use the String literal notation when possible. It is easier to read and it gives the compiler a chance to optimize our code.
5. Manual Interning
We can manually intern a String in the Java String Pool by calling the intern() method on the object we want to intern.
Manually interning the String will store its reference in the pool, and the JVM will return this reference when needed.
Let's create a test case for this:
String constantString = "interned Baeldung";
String newString = new String("interned Baeldung");
assertThat(constantString).isNotSameAs(newString);
String internedString = newString.intern();
assertThat(constantString)
.isSameAs(internedString);
6. Garbage Collection
Before Java 7, the JVM placed the Java String Pool in the PermGen space, which has a fixed size — it can't be expanded at runtime and is not eligible for garbage collection.
The risk of interning Strings in the PermGen (instead of the Heap) is that we can get an OutOfMemory error from the JVM if we intern too many Strings.
From Java 7 onwards, the Java String Pool is stored in the Heap space, which is garbage collected by the JVM. The advantage of this approach is the reduced risk of OutOfMemory error because unreferenced Strings will be removed from the pool, thereby releasing memory.
7. Performance and Optimizations
In Java 6, the only optimization we can perform is increasing the PermGen space during the program invocation with the MaxPermSize JVM option:
-XX:MaxPermSize=1G
In Java 7, we have more detailed options to examine and expand/reduce the pool size. Let's see the two options for viewing the pool size:
-XX:+PrintFlagsFinal
-XX:+PrintStringTableStatistics
If we want to increase the pool size in terms of buckets, we can use the StringTableSize JVM option:
-XX:StringTableSize=4901
Prior to Java 7u40, the default pool size was 1009 buckets but this value was subject to a few changes in more recent Java versions. To be precise, the default pool size from Java 7u40 until Java 11 was 60013 and now it increased to 65536.
java
I am all confused after reading the article on javaranch site by Corey McGlone, The author of The SCJP Tip Line. named Strings, Literally and the SCJP Java 6 Programmer Guide by Kathy Sierra (co-f...
Is String Literal Pool a collection of references to the String Object, Or a collection of Objects
Ask Question
Asked 10 years, 7 months ago
Modified 4 years, 5 months ago
Viewed 26k times 74
I am all confused after reading the article on javaranch site by Corey McGlone, The author of The SCJP Tip Line. named Strings, Literally and the SCJP Java 6 Programmer Guide by Kathy Sierra (co-founder of javaranch) and Bert Bates.
I will try to quote what Mr. Corey and Ms Kathy Sierra have quoted about String Literal Pool.
1. According to Mr Corey McGlone :String Literal Pool is a Collection of references that point to the String Objects.
String s = "Hello"; (Assume there is No object on the Heap named "Hello"), will create a String object "Hello" on the heap, and will place a reference to this object in the String Literal Pool (Constant Table)
String a = new String("Bye"); (Assume there is No object on the Heap named "Bye", new operator will oblige the JVM to create an object on the Heap.
Now the explanation of "new" operator for the creation of a String and its reference is bit confusing in this article, so I am putting the code and explanation from the article itself as it-is below.
public class ImmutableStrings
{
public static void main(String[] args)
{
String one = "someString";
String two = new String("someString");
System.out.println(one.equals(two));
System.out.println(one == two);
} }
In this case, we actually end up with a slightly different behavior because of the keyword "new." In such a case, references to the two String literals are still put into the constant table (the String Literal Pool), but, when you come to the keyword "new," the JVM is obliged to create a new String object at run-time, rather than using the one from the constant table.
Here is the diagram explaining it..
Here is the link to the Article by Corey McGlone
http://www.javaranch.com/journal/200409/Journal200409.jsp#a1
2. According to Kathy Sierra and Bert Bates in SCJP book:To make Java more memory efficient, the JVM set aside a special area of memory called the "String constant pool", when the compiler encounters a String Literal, it checks the pool to see if an identical String already exists or not. If not then it creates a new String Literal Object.
String s = "abc"; // Creates one String object and one reference variable....
that's fine, but then I was confused by this statement:
String s = new String("abc") // Creates two objects, and one reference variable.
It says in the book that.... a new String object in normal(non-pool) memory , and "s" will refer to it... whereas an additional literal "abc" will be placed in the pool.
The above lines in the book collide with the one in the article by Corey McGlone.
If String Literal Pool is a collection of references to the String object as mentioned by Corey McGlone, then why wil the literal object "abc" be placed in the pool (as mentioned in the book)?
And where does this String Literal Pool reside?
Please clear this doubt, though it won't matter too much while writing a code, but is very important from the aspect of memory management, and thats the reason I want to clear this funda.
javastringmemory-management
Share
Improve this question
edited Sep 29, 2018 at 17:33
Matt C 4,4305 5 gold badges 25 25 silver badges 43 43 bronze badges
asked Jul 28, 2012 at 10:45
Kumar Vivek Mitra 33.3k6 6 gold badges 47 47 silver badges 76 76 bronze badges 1
How the pool is managed might to some degree depend on the JVM implementation. As long as something isn't fixed by the language specification, they are free to experiment. So whether the pool holds references or objects might well depend, I believe. –
MvG
Jul 28, 2012 at 12:41
I recently came across exact same question with same 2 resources you mentioned. I think by statement object "abc" will be placed in the pool in book, author means reference to object "abc" will be stored in pool. Right? Accepted answer is pretty informative but I think this is what being asked. –
mustafa1993
Jan 27, 2017 at 8:15
Add a comment
1 Answer
112
I think the main point to understand here is the distinction between String Java object and its contents - char[] under private value field. String is basically a wrapper around char[] array, encapsulating it and making it impossible to modify so the String can remain immutable. Also the String class remembers which parts of this array is actually used (see below). This all means that you can have two different String objects (quite lightweight) pointing to the same char[].
I will show you few examples, together with hashCode() of each String and hashCode() of internal char[] value field (I will call it text to distinguish it from string). Finally I'll show javap -c -verbose output, together with constant pool for my test class. Please do not confuse class constant pool with string literal pool. They are not quite the same. See also Understanding javap's output for the Constant Pool.
String Pool in Java
Learn about String Pool in Java by Scaler Topics. String Pool or String Constant Pool is a special area in Java Heap memory where string literals are stored.
String Pool in Java
String Pool in Java
Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!Go to Challenge
Learn via video course
Java for Beginners Tarun Luthra Free 5 Enrolled: 37482 Start Learning
Overview
String pool is a storage space in the Java heap memory where string literals are stored. It is also known as String Constant Pool or String Intern Pool. It is privately maintained by the Java String class. By default, the String pool is empty. A pool of strings decreases the number of String objects created in the JVM, thereby reducing memory load and improving performance.
Scope
The article aims to:
Help understand the concept and need of String Constant Pool in Java
Explain changes in the String Pool as a result of creating new strings using the new keyword and String.intern() method
Discuss the advantages and disadvantages of String Pool in Java
Introduction
A string in Java is a set of characters which is always enclosed in double quotes. A string can also be described alternatively as an array of characters. But in addition, strings in Java are treated as objects.
Strings are immutable in nature. Immutable means they have a constant value, and even if they are altered, instead of reflecting the alterations in the original string, a new object is created. This immutability is achieved through String Pool. Let us look at the concept of String Pool.
Explore free Courses by our top instructors
Java for Beginners Tarun Luthra 37k+ enrolled
Python for Beginners
Rahul Janghu 21k+ enrolled C++ for Beginners Prateek Narang 20k+ enrolled View All
35,262+ learners have attended these Courses.
What is String Pool in Java?
String Pool in Java is a special storage space in Java Heap memory where string literals are stored. It is also known by the names - String Constant Pool or String Intern Pool. Whenever a string literal is created, the JVM first checks the String Constant Pool before creating a new String object corresponding to it.
Let us first discuss the memory allocation methods used in Java - Stack Memory Allocation and Heap Memory Allocation.
In stack memory, only the primitive data types like- int, char, byte, short, boolean, long, float and double are stored.
Whereas, in the heap memory, non-primitive data types like strings are stored. A reference to this location is held by the stack memory.
Example:Since int and double are primitive data types, they are stored in the stack memory itself.
However, idName stores a String that is non-primitive in nature. Hence, the String object is created in the heap memory, and its reference is stored by idName in the stack memory.
Memory Allocation in the String Pool
The String Pool is empty by default, and it is maintained privately by the String class.
When we create a string literal, the JVM first checks that literal in the String Constant Pool. If the literal is already present in the pool, its reference is stored in the variable.
However, if the string literal is not found, the JVM creates a new string object in the String Constant Pool and returns its reference.
Need of String Constant Pool:When we create a String object, it uses some amount of space in the heap memory.
Let's say we are creating n number of String objects with the same value, and distinct memory is allocated to each of these string objects (though they all contain the same string).
This is an inefficient usage of heap memory. In order to escalate the performance of our code and reduce memory usage, JVM optimizes the way in which strings are stored with the help of a string constant pool.
Ways to Create Strings
There are three popular ways of creating strings in Java:
String literal Using new keyword
Using String.intern() method
Let us understand each of these three methods and their impact on the String Pool.
1. String literal
This is the simplest and most direct way to declare a string. It is done using double quotes.
Syntax:String = “String str = "Java";
String str1 = "Java";
String str2 = "Study";
Changes in the String Pool:The String Pool is empty by default. Hence, when the compiler executes the first line, it creates a string literal "Java" in the String Constant Pool.
When the compiler executes the second line, it first checks the String Constant Pool. Since the string literal "Java" is already present in the String Pool, its reference is stored in str1.
As a result of the execution of the third statement, a new string literal "Study" is created in the String Constant Pool (since it is not already present). Its reference is stored in str2.
The figure shows the memory allocation of the above code.
Guys, does anyone know the answer?