7-编译期常量与运行期常量的区别及数组创建本质分析

编译期常量与运行期常量的区别及数组创建本质分析

1.常量的值并非在编译期间可以确定

/**
 * 当一个常量的值并非在编译期间可以确定,那么其值就不会被放到调用类[:MyTest3]的常量池中,
 * 这时在程序运行时,会导致主动使用这个常量所在的类,显然会导致这类[:Parent3]被初始化。
 */
public class MyTest3 {
    public static void main(String[] args) {
        System.out.println(Parent3.str);
    }
}
class Parent3 {
    public static final String str = UUID.randomUUID().toString();
    static {
        System.out.println("This is Parent3's static");
    }
}
运行结果:
   This is Parent3's static
   5161b1ac-c574-431c-9485-3537cc239821

2.首次主动使用时才能初始化,再次使用时,不在进行初始化

public class MyTest4 {
    public static void main(String[] args) {
        Parent4 parent4 = new Parent4();
        System.out.println("==========");
        Parent4 parent41 = new Parent4();
    }
}
class Parent4 {
    static {
        System.out.println("This is Parent4's static");
    }
}
运行结果:
   This is Parent4's static
   ==========

3.数组:不属于主动使用的任何一种,而且类型是在JVM运行期才创建出来

/*
	对于数组实例来说,其类型是由JVM在运行期动态生成的,表示为:[LJvm.Parent4;这种形式,动态生成的类型,其父类型就是Object。
	对于数字来说,JavaDoc经常将组成数组的元素为Component,实际上就是将数组降低一个维度后的类型。
	助记符:
		anewarray:表示创建一个引用类型的(如类、接口、数组)数组,并将其引用值压入栈顶。
		newarray:表示创建一个指定的原始类型(如int,float,char等)的数组,并将其值压入栈顶。
*/
public class MyTest4 {
    public static void main(String[] args) {
        Parent4[] parent4 = new Parent4[1];
        System.out.println(parent4.getClass());
        Parent4[][] parent4s = new Parent4[1][1];
        System.out.println(parent4s.getClass());
       
        System.out.println(parent4.getClass().getSuperclass());
        System.out.println(parent4s.getClass().getSuperclass());
       
        System.out.println("=============");
        int[] a = new int[1];
        System.out.println(a.getClass());
        System.out.println(a.getClass().getSuperclass());
       
        char[] chars = new char[1];
        System.out.println(chars.getClass());

        boolean[] booleans = new boolean[1];
        System.out.println(booleans.getClass());

        short[] shorts = new short[1];
        System.out.println(shorts.getClass());

        byte[] bytes = new byte[1];
        System.out.println(bytes.getClass());
    }
}
class Parent4 {
    static {
        System.out.println("This is Parent4's static");
    }
}
运行结果:
   class [LJvm.Parent4;
   class [[LJvm.Parent4;
   class java.lang.Object
	class java.lang.Object
	=============
	class [I
	class java.lang.Object
	class [C
   class [Z
   class [S
   class [B
   说明:数组不是没有初始化,而是说初始化的时候,初始化的对象并不是Parent4,而是class [LJvm.Parent4,class [[LJvm.Parent4。
发布了12 篇原创文章 · 获赞 0 · 访问量 226

猜你喜欢

转载自blog.csdn.net/qq_40574305/article/details/104783919