`
zwt2001267
  • 浏览: 433320 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

What is Java String Pool?

    博客分类:
  • Java
 
阅读更多

java字符串常量池,作用类似缓存,节省heap空间和加快对象生成:

测试代码:

 

public class Start {
	public static void main(String[] args) {
		String s1 = "abc";
		String s2 = "abc";
		String s3 = new String("abc");
		String s4 = new String("abc").intern();
		
		System.out.println(s1 == s2);
		System.out.println(s1.equals(s2));
		System.out.println("=========");
		System.out.println(s1 == s3);
		System.out.println(s1.equals(s3));
		System.out.println("=========");
		System.out.println(s1 == s4);
		System.out.println(s1.equals(s4));
	}
}

 

 

 测试结果:

true

true

=========

false

true

=========

true

true

 

为何s1 == s2 为true?

http://www.journaldev.com/797/what-is-java-string-pool

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-Java

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:

StringPool.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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:

1
2
s1 == s2 :true
s1 == s3 :false
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics