String and String pool in java

What is String ?

  1. String is non-premitive data type
  2. String is a sequence of characters (String is array of characters)
    char c = {‘c’,’k’,’e’}; //charSequence interface used to represent string
    String s = new String(c);
  3. String is a class and it is a final class
    public final class String extends Object implements CharSequence,Serializable,Comparable{ }
  4. String s = new String();
    This creates a immutable object
  5. String can be created in two ways
    String s1 = “abc”;
    String s2 = new String(“abc”);
  6. We can create String Object using 3 classes, String, StringBuffer and StringBuilder
  7. Strings are immutable there by making it thread safe

String Constant Pool (SCP)

  1. Until Java 1.6 String Constant Pool resided in Method Area, from 1.7 it resides in the heap memory. (Reason: Memory was constant in Method Aread but Heap Size can increase its size)
  2. Garbage collection never happens in String Constant pool
  3. When a String is created with the new keyword,
    Example: String s1 = new String(“abc”); //2 objects are created
    • it is stored in Heap Area,
    • but if it contains a literal with double quotes like “abc” then an object is also created in String Constant Pool.
    • String Constant Pool Object is pointed by an internal reference created by JVM.
    • Note: The reason 2nd object is created in the String Constant pool is that it could be used in the future.
  4. When a String is created as below
    Example : String s2 = “xyz”
    This string is directly created in String Constant Pool and only 1 object is created
  5. When below operation is performed
    String s1 = new String(“abc”); //Line 1
    s1=s1.concta(“pqr”); //Line 3
    s1.concat(“xyz”); //Line 2
    Note : Same concept is applied when + symbol is used instead on concat.
    1. At 1st line “abc” String object is created in SCP and it is also created in Heap and it is pointed by s1 reference.
    2. At 2nd line “pqr” String object is created in SCP and string “abcpqr” is created in Heap and s1 reference is pointed to “abcpqr” in heap and “abc” object in heap is eligible for garbage collection.
    3. At 3rd line “xyz” String object is created in SCP and string “abcpqrxyz” is created in Heap but is also eligible for garbage collection since no reference is pointing to the string “abcpqrxyz”
  6. Run time operations like + or .concat will always create object in heap and string literals like “abc” is compile time and it is stored in SCP
  7. When below operation is performed
    String s1=”abc” //SCP
    s1=s1.concat(“xyz”)//Run time operation s1 is Heap and “xyz” in SCP
    s1=”pqr”+”uvw”//Compile time operations s1 is in SCP
What is the importance of SCP(String constant pool)? - Java4us

Why String Constant Pool ?

  1. the string constant pool exists mainly to reduce memory usage and improve the re-use of existing instances in memory. When a string object is assigned a different value, the new value will be registered in the string constant pool as a separate instance. 
  2. One way to skip this memory allocation is to use the new keyword while creating a new string object. The ‘new’ keyword forces a new instance to always be created regardless of whether the same value was used previously or not. Using ‘new’ forces the instance to be created in the heap outside the string constant pool which is clear, since caching and re-using of instances isn’t allowed here.

String Immutability

  1. What is Immutable? Immutable are things that cannot be changed
  2. Why String is immutable?
    1. String objects are cached inside the String pool.
    2. These cached String Objects are shared by multiple String references.
    3. So if we change the actual value of the String Object, it could change the value of other references that are pointing to that String object.
    4. Hence we never modify a String Object in String Pool instead we create a new object in String Constant Pool.
    5. Hence Strings are immutable

String is a final Class

No other class will be able to extend the String class and modify its contents

String intern method

  • Intern method is add a String into String Costant pool
  • If the String already exist in String Constant pool then that objects reference is returned.

String .equals() method and == operator

  • .equals method is used to compare the contents of the string
  • == operator is used to compare the reference of the string

String Constructors

String methods

Search in String

  • indexOf
  • lastIndexOf
  • charAt
  • contains
  • startsWith
  • endsWith
  • substring (returns String)
  • subSequence (returns character array)
  • concat
  • join
  • replace
  • replaceFirst
  • replaceAll

String Buffer

  • StringBuffer create mutable object
  • We can use .append() method to add String
  • All the methods in StringBuffer are synchronized which causes the threads to execute only 1 thread at a time and there is also a lock involved in it which effects the performance

String Builder

  • Introduced in java 1.5
  • StringBuilder exactly the same as StringBuffer but the methods are non syncronized
  • So the efficiency is more compare to StringBuilder is a concurrent environment
  • Same methods of StringBuffer is used in StringBuilder

Difference between String, StringBuffer and StringBuilder

StorageHeap Area and SCPHeap AreaHeap Area
ObjectImmutable objectMutable ObjectMutable Object
MemoryIf we change data a lot more memory is consumedconsumes less memoryconsumes less memory
Thread Safenot Thread-safeAll methods are synchronized and thus is Thread-safeNot Synchronized hence not Thread-safe
PerformanceSlowFast compared to StringFast compared to StringBuffer
UsageIf data is not changing frequentlyIn a multithreaded environment where data changes frequentlyIn Thread-safe environment where data changes frequently

Interview Questions :

  • WAP to Reverse a String (chatAt())
  • WAP to check palindrome (chatAt())
  • WAP to find max and min occurring char in String
  • WAP to count the number of words in String
  • WAP to print all permutations of a String
  • WAP to print the duplicate character from the given String
  • WAP to remove the characters from 1st String which are present in 2nd String
  • WAP to find non-repetitive characters in string
  • WAP to check if strings are anagram of each other
  • WAP to split comma separated String in java

Proof String is immutable :

public class ProofStringIsImmutable {
	public static void main(String[] args) {
		String s1 = "ABC";
		String s2 = s1;

How many objects are created while String s = new String(“ABC”); ?

Inside java heap memory there is a string constant pool.
When String s = new String("ABC"); 
Since new is used here the object has to be created in the heapmemory itself but it checkes if the entry of "ABC" exist in the String constant pool as well, and if it does not exist then it will make an entry into the string constant pool. But it will refear to the Object created in the heap only.

String methods :

Reference :

Youtube – PlayList

Leave a Comment