Let’s list out points to know facts about string:
  1. String is a set of literals. It is a collection of literals backed by array. We can get character array by calling toCharArray() method of String class.
  2. String is final. We cannot change String. When you perform any operation on String, JVM will create new reference in memory.
  3. Strings are stored in String Pool. All String object resides inside String Pool created with double quote. JVM will check object first in String Pool if it is available then it will assign the same object else it will create new object in String Pool and return the same. String Pool will contain unique String object in the Pool. JVM does not perform check in String Pool if it is created using new operator. You can put object in String Pool by calling intern() method too.
  4. equals() method is overridden in String class to compare string by its character value.
What is String Pool?

String Pool is a special memory location inside Java memory, more precisely inside PermGen Space.

It is a implementation of the Flyweight pattern. It means when lots of data is common among objects, it would be better to just share the same instance of that data than creating several different copies of it.

Below diagram illustrate memory management for String Pool.

Below example explains it is creating single object for same value:

Output: true true

Memory assignment of String is case sensitive. There will be different storage for different case insensitive strings.

Key Point: If there are too many String there is good chance of OutOfMemoryError because garbage collection doesn’t happen in PERM area of java heap.

Reference Docs :
Oracle java.lang.String

Leave a Reply

Your email address will not be published. Required fields are marked *