The java.lang.String class provides a way to work with a sequence of characters.
String is a class(not a primitive ) and also you can say a reference type.
- Primitive Types (int, float, etc) : They directly hold the values in memory.
- Reference Type (String, Array, List, object) : These store the memory addresses (references) of an object in the heap
Ways to Create a String Object.
a) Using the new keyword.
String s1 = new String ("Hello");
b) Using string literals.
String s2 = "Hello"
Interning
String s = "Hello"
The String literal “Hello” is stored in the String Pool ( a part of the Heap memory). The variable ‘s’ holds a reference (a memory address) pointing to the location of “Hello” in the String Pool.
String s2 = "Hello";
Here ‘s2‘ will reference the same object in the String Pool as ‘s‘ as String literals with the same values will be shared.
Interning refers to a mechanism for optimizing memory usage by ensuring that identical String objects share a single instance in a special memory area called the String Pool. This process avoids creating duplicate String Objects with the same content.
So when a String literal is created, the JVM first checks the pool:
- If a literal already exists in the pool, a reference to the existing object is returned.
- If a literal doesn’t exist. it is added to the pool and a reference to the new object is returned.
Explicit Interning: The intern() method in the String class forces a String Object to be added to the pool.
Lets see how to initialize using two methods:
#String Literal Initialization
String a = "Hello"
String b = a;
String c = "Hello";
Here all the variables share the same reference.
(a==b) ; #True
(a==c) ; #True
(b==c) ; #True
#Using the new Keyword
char[]text = {'H','e','l','l','o'};
String a = new String(text); #creates a new String object and does not reuse the interned "Hello" because of using the new keyword.
String b = new String("Hello"); #Creates a new String Object
(a == b); #false
String c = a.intern();
(c == d); #True
The intern() method ensures that String object refers to the interned version in the String Pool.