执行一段代码,解释内存变更
JVM系列(1)java8内存结构
String相关题目
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| public static void main(String[] args) { String s1 = "hello"; String s2 = "hello"; String s3 = "he" + "llo"; String s4 = "hel" + new String("lo"); String s5 = new String("hello"); String s6 = s5.intern(); String s7 = "h"; String s8 = "ello"; String s9 = s7 + s8; System.out.println(s1==s2); System.out.println(s1==s3); System.out.println(s1==s4); System.out.println(s1==s9); System.out.println(s4==s5); System.out.println(s1==s6); }
|
在jdk1.6,1.7,1.8下运行的结果为:
System.out.println(s1==s2);//true
System.out.println(s1==s3);//true
System.out.println(s1==s4);//false
System.out.println(s1==s9);//false
System.out.println(s4==s5);//false
System.out.println(s1==s6);//true
1 2 3 4 5 6 7 8 9 10
| public static void main(String[] args) { String s1 = new String("hello"); String intern1 = s1.intern(); String s2 = "hello"; System.out.println(s1 == s2); String s3 = new String("hello") + new String("hello"); String intern3 = s3.intern(); String s4 = "hellohello"; System.out.println(s3 == s4); }
|
在jdk1.6下运行的结果为:
false,false
在jdk1.7,1.8下运行的结果为:
false,true
1 2 3 4 5 6 7 8 9 10
| public static void main(String[] args) { String s1 = new String("hello"); String s2 = "hello"; String intern1 = s1.intern(); System.out.println(s1 == s2); String s3 = new String("hello") + new String("hello"); String s4 = "hellohello"; String intern3 = s3.intern(); System.out.println(s3 == s4); }
|
在jdk1.6下运行的结果为:
false,false
在jdk1.7,1.8下运行的结果为:
false,false
Java中String字符串常量池
String.intern()引发的性能问题
Java中的常量池(字符串常量池、class常量池和运行时常量池)
JVM系列(1)java8内存结构
Java中的常量池(字符串常量池、class常量池和运行时常量池)
java常量池-字符串常量池、class常量池和运行时常量池
方法区和常量池
[What is Run-Time Constant Pool and Method-Area in java](https://stackoverflow.com/questions/22921010/what-is-run-time-constant-pool-and-method-area-in-java)
字符串池和字符串常量池的区别
《Java虚拟机原理图解》 1.2.2、Class文件中的常量池详解(上)
注意字符串常量池和字符串池的区别,翻译问题?
1 2 3 4
| String s3 = new String("hello") + new String("hello"); s3.intern(); String s4 = "hellohello"; System.out.println(s3 == s4);
|
只有在程序里面需要用到字符串的时候,才会去堆中创建字符串对象,然后把引用返回给字符串常量池。