近日,有一个网友在小密圈提了一个问题,我本来觉得这个问题应该挺简单的,没想到这个问题在圈子里引起了广泛的讨论。 问题:前辈,请教个问题,下面两行代码,会在JAVA字符串常量池中产生几个字符串。 String str1 = "ab"; String str2 = str1 + "c"; 对这个引起热烈讨论的问题,我本来想写一篇深度讲解的文章,结果在网上发现了一篇很优秀的关于此题原理的文章,先分享给大家。
作为最基础的引用数据类型,Java 设计者为 String 提供了字符串常量池以提高其性能,那么字符串常量池的具体原理是什么,我们带着以下三个问题,去理解字符串常量池:
代码:从字符串常量池中获取相应的字符串
String str1 = “hello”;
String str2 = “hello”;
System.out.printl("str1 == str2" : str1 == str2 ) //true
在分析字符串常量池的位置时,首先了解一下堆、栈、方法区:
堆
存储的是对象,每个对象都包含一个与之对应的class
JVM只有一个堆区(heap)被所有线程共享,堆中不存放基本类型和对象引用,只存放对象本身
对象的由垃圾回收器负责回收,因此大小和生命周期不需要确定
栈
每个线程包含一个栈区,栈中只保存基础数据类型的对象和自定义对象的引用(不是对象)
每个栈中的数据(原始类型和对象引用)都是私有的
栈分为3个部分:基本类型变量区、执行环境上下文、操作指令区(存放操作指令)
数据大小和生命周期是可以确定的,当没有引用指向数据时,这个数据就会自动消失
方法区
静态区,跟堆一样,被所有的线程共享
方法区中包含的都是在整个程序中永远唯一的元素,如class,static变量
字符串常量池则存在于方法区
代码:堆栈方法区存储字符串
String str1 = “abc”;
String str2 = “abc”;
String str3 = “abc”;
String str4 = new String(“abc”);
String str5 = new String(“abc”);
字符串对象的创建
面试题:String str4 = new String(“abc”) 创建多少个对象?
所以,常量池中没有“abc”字面量则创建两个对象,否则创建一个对象,以及创建一个引用
根据字面量,往往会提出这样的变式题:
String str1 = new String("A"+"B") ; 会创建多少个对象? String str2 = new String("ABC") + "ABC" ; 会创建多少个对象?
str1: 字符串常量池:"A","B","AB" : 3个 堆:new String("AB") :1个 引用: str1 :1个 总共 : 5个
str2 : 字符串常量池:"ABC" : 1个 堆:new String("ABC") :1个 引用: str2 :1个 总共 : 3个
代码:基础类型的变量和常量,变量和引用存储在栈中,常量存储在常量池中
int a1 = 1;
int a2 = 1;
int a3 = 1;
public static int INT1 =1 ;
public static int INT2 =1 ;
public static int INT3 =1 ;
操作字符串常量池的方式
String str1 = “hello”;
String str2 = “hello”;
System.out.printl("str1 == str2" : str1 == str2 ) //true
通过new操作符创建的字符串对象不指向字符串池中的任何对象,但是可以通过使用字符串的intern()方法来指向其中的某一个。java.lang.String.intern()返回一个保留池字符串,就是一个在全局字符串池中有了一个入口。如果以前没有在全局字符串池中,那么它就会被添加到里面
// Create three strings in three different ways.
String s1 = "Hello";
String s2 = new StringBuffer("He").append("llo").toString();
String s3 = s2.intern();
// Determine which strings are equivalent using the ==
// operator
System.out.println("s1 == s2? " + (s1 == s2)); // false
System.out.println("s1 == s3? " + (s1 == s3)); // true
字符串对象内部是用字符数组存储的,那么看下面的例子:
String m = "hello,world";
String n = "hello,world";
String u = new String(m);
String v = new String("hello,world");
使用图来表示的话,情况就大概是这样的(使用虚线只是表示两者其实没什么特别的关系):
测试demo:
String m = "hello,world";
String n = "hello,world";
String u = new String(m);
String v = new String("hello,world");
System.out.println(m == n); //true
System.out.println(m == u); //false
System.out.println(m == v); //false
System.out.println(u == v); //false
结论:
原文出处:https://segmentfault.com/a/1190000009888357#articleHeader0