String Pool or Intern pool
Strings are everywhere in Java, they use a lot of memory. How does Java solves this problem?
Answer : It collects all this strings and store them in a location called String Pool or Intern Pool in JVM. This location contains literal values and constants that appears in your program.
Consider the following
var x = "Hello World";
var y = "Hello World";
System.out.println(x == y);
JVM creates one literal in memory and both x and y point's to the same location in the memory. Therefore it prints true.
How about the following?
var x = "Hello World";
var y = " Hello World".trim();
System.out.println(x==y)
This will be false. Although, x and y evaluates to the same value one is computed at runtime and the other is at compile time. How about a simple simple concatenation like the following?
var x = "hello world";
var y = "hello";
y += " world";
System.out.println(x==y);
This will also be false as concatenation is the same as calling a method.
What is the difference between the two statements below?
var x = "Hello World";
var y = new String("Hello World");
First, one says to use the normal String Pool while the second one says "No JVM, No String Pool, Just Please Create a New Object"
How about if we want to force the String object created by "new" to refer to the String Pool?
var y = new String("Hello World").intern();
#Java #StringPool