string pool trong java

What is String Pool?

String Pool in Java is a special memory region managed by the JVM (Java Virtual Machine), used to store String objects.

The purpose of the String Pool is to save memory and improve performance by reusing identical strings instead of creating new ones.

How String Pool Works

When a string is created using a literal (a string directly in double quotes), the JVM checks whether that string already exists in the String Pool:

  • If it exists, the JVM returns a reference to that string.
  • If it doesn’t, the JVM creates a new String object and stores it in the String Pool.

Example:

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

        System.out.println(s1 == s2); // true - same reference in the String Pool
    }
}

The result is true because s1 and s2 both reference the same object in the String Pool.

String Created with new

When a string is created using the new keyword, the JVM always creates a new String object in the heap memory, not using the String Pool.

Example:

public class StringNewExample {
    public static void main(String[] args) {
        String s1 = new String("Hello");
        String s2 = new String("Hello");

        System.out.println(s1 == s2); // false - different references in the heap
        System.out.println(s1.equals(s2)); // true - same content
    }
}

intern() Method

The intern() method is used to move a string to the String Pool (if it isn’t already there) or return a reference to the string in the Pool (if it is).

Example:

public class StringInternExample {
    public static void main(String[] args) {
        String s1 = new String("Hello");
        String s2 = s1.intern();
        String s3 = "Hello";

        System.out.println(s2 == s3); // true - same reference in the String Pool
    }
}

Why is String Pool Important?

  • Improves performance: Reusing existing strings reduces memory allocation and deallocation.
  • Saves memory: Avoids creating multiple identical String objects.
  • Optimizes GC (Garbage Collection): Reduces the load on GC due to fewer objects.

Conclusion

The String Pool is an important feature in Java that helps manage memory efficiently. Understanding how the String Pool works will help Java developers write more optimized code.

I hope this article helps you grasp the String Pool concept and apply it to your Java projects!

Leave a Reply

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

Post comment