验证常量池中的字符串仅是符号,第一次用到时才变为对象

接上文连接:StringTable

测试用例:

/**
 * 演示字符串字面量也是【延迟】成为对象的
 */
public class TestString {
    public static void main(String[] args) {
        int x = args.length;
        System.out.println(); // 字符串个数 2275

        System.out.print("1");
        System.out.print("2");
        System.out.print("3");
        System.out.print("4");
        System.out.print("5");
        System.out.print("6");
        System.out.print("7");
        System.out.print("8");
        System.out.print("9");
        System.out.print("0");
        System.out.print("1"); // 字符串个数 2285
        System.out.print("2");
        System.out.print("3");
        System.out.print("4");
        System.out.print("5");
        System.out.print("6");
        System.out.print("7");
        System.out.print("8");
        System.out.print("9");
        System.out.print("0");
        System.out.print(x); // 字符串个数
    }
}

如何测试呢,我们利用IDEA中的debug模式下的Memory框进行检测

这个Memory是用来分析jvm堆中的对象。

引用一下IDEA的官方介绍吧。

Memory官方文档

The Memory view shows you the total number of objects in the heap:

When you step over the code, the Diff column shows how the number of objects changes between the debugger stops, which helps you see how the code you are stepping affects the heap.

Double-click a class name to view all instances of this class:


以Debug模式运行程序



可以发现还是2365,观察程序,因为运行时常量池中已经有了该对象了, 自然不会再重复创建了。

原文地址:https://www.cnblogs.com/heliusKing/p/12005501.html