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。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值