String Class(Since JDK 1.0)

A String can be constructed by either:
  • directly assigning a string literal to 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:
memory layout of String literals
Optimization of String Memory Allocation:
  • The String Literals (Which have same value) can store in String Pool thus the String Objects are store in Heap.
  • first type of creation is much more faster, Why?
  • The "new" key word creates new objects for s4 and s5 which is expensive.
  • Java maintains an internal list of references for interned Strings pool of unique Strings to 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 Collected even JVM executes its Full GC.
  • It Means String Class make large Garbage.