最近看JVM的时候,看到一个很有意思的题目,如下
String s1 = new String("111");
String s2 = "111";
String s3 = s1.intern();
System.out.println(s1 == s2);
System.out.printlin(s2 == s3);
第一个返回的结果是false
第二个返回的结果是true
s1实例指向的是堆,s2指向的是字符串常量池,s1的intern()方法并不会将原本指向堆内存的s1,改为指向常量池,而是复制一个s1的副本指向常量池中,intern()方法也有注释
When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
当intern()方法被调用,如果池中已经有了这个String对象,那么直接返回,另一方面如果没有那么就将这个String对象添加到池中,并返回这个字符串的引用。
另外知识补充:
java中基本类型的包装类的大部分都实现了常量池技术,即Byte,Short,Integer,Long,Character,Boolean。这5种包装类默认创建了数值[-128,127]的相应类型的缓存数据,但是超出此范围仍然会去创建新的对象。 两种浮点数类型的包装类Float,Double并没有实现常量池技术。