String Class(Since JDK 1.0)
A String can be constructed by either:
- directly assigning a
string literalto a String reference - just like a primitive, or - via the
"new"operator and constructor, similar to any other classes.However, this is not commonly-used and is not recommended.
Example:
Memory Layout of String Literals and String Object:
Optimization of String Memory Allocation:
- The String Literals (Which have same value) can store in
String Poolthus the String Objects are store in Heap. first type ofcreation is muchmore faster, Why?- The
"new"key word creates new objects for s4 and s5 which isexpensive. - Java maintains an internal list of references for interned
Strings
pool of unique Stringsto avoid duplicate String objects in heap memory. - When we making an String Object then the one copy of that String store in String Pool and another in Heap.
- String Pool is mainly situated in
PermGen(Permanent Generation). - PermGen
never be Garbage Collectedeven JVM executes its Full GC. - It Means String Class make
large Garbage.


