48. What is String pool?

What is String pool?

String pool is a special storage area in heap memories.
It is used to improve the performance of the system. It like a cache memory contains all the String literals.


When we create a String Object with String literal. First, it will be check in the string pool whether that String literal have existed in String pool or not.
If it has existed –> it will be return that String literal

If it has not existed –> it will be creating a new one and return it.

Example:

 

public class StringPoolExample {
public static void main(String[] args) {
String str1 = “Hello”;
String str2 = “Hello”;
String str3 = new String(“Hello”);

// Comparing string literals (from the string pool)
System.out.println(“str1 == str2: ” + (str1 == str2)); // true

// Comparing string literal with a new String object
System.out.println(“str1 == str3: ” + (str1 == str3)); // false

// Comparing the contents of the strings
System.out.println(“str1.equals(str3): ” + str1.equals(str3)); // true
}
}

Leave a Reply

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