What is the String constant pool in Java, and what exactly gets interned into it?
The string constant pool is a place in memory where Java keeps the text that it has been given as a literal. When the same text appears in your code more than once, the compiler arranges for all of those places to share one copy of it.
So what ends up in the pool? The text that you write as a literal in your source code. The line String name = "hello"; puts the text "hello" into the pool. If another part of your program also writes "hello" as a literal, it gets the very same object, so the two variables point at one string in memory.
public class Main {
public static void main(String[] args) {
String literal = "hello";
String literal2 = "hello";
// The same object, because both came from the pool.
System.out.println("same object : " + (literal == literal2));
// Text made at run time is not in the pool.
String made = new String("hello");
System.out.println("made object : " + (literal == made));
System.out.println("same text : " + literal.equals(made));
}
}
Text that you build while the program is running is not put into the pool automatically. The line new String("hello") always makes a new object, even though the text is the same as the literal.
There is one method that lets you put a string into the pool yourself, and it is called intern. After you call it, the string that it returns is the pooled one, so it is the same object as any other pooled string with the same text.
The next question in this topic shows you how to look at the pool from inside a program.