/* 字符串拼接操作
● 常量与常量的拼接结果在常量池,原理是编译期优化
● 常量池中不会存在相同内容的变量
● 只要其中有一个是变量,结果就在堆中。变量拼接的原理是StringBuilder
● 如果拼接的结果调用intern()方法,则主动将常量池中还没有的字符串对象放入池中,并返回此对象地址
*/
String s = new String("a")+new String("b");//new String ("ab")
System.out.println(s =="ab");//false
String s1 = new String("c")+new String("d");//此时堆内创建对象实例,但字符串常量池中并没有常量"cd"
s1.intern();//将cd复制到常量池
System.out.println(s1=="cd");//true
String x="ef";
String s2 = new String("e") + new String("f");
s2.intern();
System.out.println(s2 =="ef"); //false
String s3 = new String("g") + new String("h");
String s4 = s3.intern();
System.out.println(s3=="gh");//true
System.out.println(s3==s4);//true
String s5 = new String("ij");//此时堆内创建对象实例,并且在字符串常量池中创建常量"ij"
s5.intern();//不起作用
System.out.println(s5=="ij");//false 堆中存在值为ij的对象,字符串常量池中存在字符串ij,这俩不是同一内存地址
String s6="kl";//没有对象实例,只在字符串常量池中创建"kl"
System.out.println(s6=="kl");//true
String x1="abc";
String x2="def";
String x3=x1+x2;//只要其中有一个是变量,结果就在堆中。变量拼接的原理是StringBuilder
System.out.println(x3=="abcdef");//false x3指向堆空间的对象实例,abcdef是字符串常量池中的字符串
String y3="efg"+"hij";
System.out.println(y3=="efghij");//true
String z1="aabb";
String z2="ccdd";
String z3=z1+z2;//只要其中有一个是变量,结果就在堆中。变量拼接的原理是StringBuilder
String z4= z3.intern(); //将z3对象的值复制到字符串常量池中z3的就指向了字符串常量池
System.out.println(z3=="aabbccdd");//true x3与常量池中的字符串是相同的地址
System.out.println(z4=="aabbccdd");//true x4是常量池中的字符串
字符串拼接原理及字符串中jvm中存储位置
最新推荐文章于 2022-07-28 17:02:45 发布