字符串常量池及intern()方法
字符串常量池
面试题code
public class StringPool58Demo {
public static void main(String[] args) {
String str1 = new StringBuilder("58").append("tongcheng").toString();
System.out.println(str1); // 58tongcheng
System.out.println(str1.intern()); // 58tongcheng
System.out.println(str1 == str1.intern()); //true
System.out.println("------------");
String str2 = new StringBuilder("ja").append("va").toString();
System.out.println(str2); // java
System.out.println(str2.intern()); // java
System.out.println(str2 == str2.intern()); // false ⚠️ 有一个初始化的java字符串(JDK出娘胎自带的), 在加载sun.misc.Version这个类的时候进入常量池
}
}
intern()方法
为什么
有一个初始化的java字符串(JDK出娘胎自带的), 在加载sun.misc.Version这个类的时候进入常量池
OpenJDK8底层源码说明
1.System代码解析
public final class System {
/* register the natives via the static initializer.
*
* VM will invoke the initializeSystemClass method to complete
* the initialization for this class separated from clinit.
* Note that to use properties set by the VM, see the constraints
* described in the ⚠️initializeSystemClass method.
*/
...
/**
* Initialize the system class. Called after thread initialization. 在线程初始化后被调用
*/
private static void initializeSystemClass() {
...
sun.misc.Version.init();
...
}
}
// sun.misc.Version.init()方法所在类
package sun.misc;
import java.io.PrintStream;
public class Version {
private static final String launcher_name = "java"; ⚠️
private static final String java_version = "1.8.0_261";
private static final String java_runtime_name = "Java(TM) SE Runtime Environment";
private static final String java_profile_name = "";
private static final String java_runtime_version = "1.8.0_261-b12";
}
2.类加载器和rt.jar
根加载器提前部署加载rt.jar
3.OpenJDK8源码
- http://openjdk.java.net/
- openjdk8\jdk\srclshare\classes\sun\misc
考查点
- intern()方法,判断true/false?
- 《深入理解java虚拟机》书原题 是否读过经典JM书籍
既已览卷至此,何不品评一二: