Java String Pool

来源:互联网 发布:知盈医学课堂网址 编辑:程序博客网 时间:2024/05/16 16:12

As the name suggests, String Pool is a pool of Strings stored in Java heap memory. We know that String is special class in java and we can create String object using new operator as well as providing values in double quotes.

Here is a diagram which clearly explains how String Pool is maintained in java heap space and what happens when we use different ways to create Strings.


String Pool is possible only because String is immutable in Java and it’s implementation of String interningconcept. String pool is also example of Flyweight design pattern.

String pool helps in saving a lot of space for Java Runtime although it takes more time to create the String.

When we use double quotes to create a String, it first looks for String with same value in the String pool, if found it just returns the reference else it creates a new String in the pool and then returns the reference.

However using new operator, we force String class to create a new String object and then we can useintern() method to put it into the pool or refer to other String object from pool having same value.

Here is the java program for the String Pool image:

package com.journaldev.util;public class StringPool {    /**     * Java String Pool example     * @param args     */    public static void main(String[] args) {        String s1 = "Cat";        String s2 = "Cat";        String s3 = new String("Cat");                System.out.println("s1 == s2 :"+(s1==s2));        System.out.println("s1 == s3 :"+(s1==s3));    }}

Output of the above program is:

s1 == s2 :trues1 == s3 :false

原创粉丝点击