常量池在java用于保存在编译期已确定的,已编译的class文件中的一份数据。它包括了关于类,方法,接口等中的常量,也包括字符串常量,如String s = “java”;可扩充( String.intern()方法 ),执行器产生的常量也会放入常量池,故认为常量池是JVM的一块特殊的内存空间。
String str1 = new String("abc");
String str2 = "abc";
请到这位大神的博客中查看:
https://blog.csdn.net/shy244/article/details/80994059
String str1 = new String("A"+"B") ;
String str2 = new String("ABC") + "ABC" ;
String str1 = "abc"; //pool
String str2 = "abc"; //pool
String str3 = new String("abc"); //heap
String str4 = new String("abc"); //heap
System.out.println(str1 == str2); //1
System.out.println(str2 == str3); //2
System.out.println(str3 == str4); //3
true
false
false
String str5 = str4; //heap
String str6 = str4.intern(); //pool
String str7 = str1; //pool
System.out.println(str4 == str5); //1
System.out.println(str4 == str6); //2
System.out.println(str1 == str2); //3
System.out.println(str1 == str7); //4
true
false
true
true
str4.intern();
System.out.println(str4 == str1); //1
str4 = str4.intern(); //pool
System.out.println(str4 == str1); //2
false
true
String s1 = "Master";
String s2 = new String("Master");
final String s3 = "Master";
String s4 = "AndyMaster"; //pool
String s5 = "Andy" + "Master"; //pool
String s6 = "Andy" + s1; //heap
String s9 = "Andy" + s1; //heap
String s7 = "Andy" + s2; //heap
String s8 = "Andy" + s3; //pool
System.out.println(s4 == s5); //1
System.out.println(s4 == s6); //2
System.out.println(s4 == s7); //3
System.out.println(s4 == s8); //4
System.out.println(s6 == s9); //5
true
false
false
true
false
字符串对象内部是用字符数组存储的,那么看下面的例子:
String m = "hello,world";
String n = "hello,world";
String u = new String(m);
String v = new String("hello,world");
String m = "hello,world";
String n = "hello,world";
String u = new String(m);
String v = new String("hello,world");
System.out.println(m == n);
System.out.println(m == u);
System.out.println(m == v);
System.out.println(u == v);
true
false
false
false
参考:
https://segmentfault.com/a/1190000009888357
https://blog.csdn.net/xdugucc/article/details/78193805