JVM 静态变量内存分配探究

好记忆不如烂笔头,能记下点什么,就记下点什么,方便后期的查看.

二话不说,

先看代码一和输出 : 

public class Test {
    private int count1;
    private int count2=2;
    public Test(){
        count1++;
        count2++;
        System.out.println(""+count1);
        System.out.println(""+count2);
    }
    public static void main(String[] args) {
        Test t=new Test();
        System.out.println(""+t.count1);
        System.out.println(""+t.count2);
    }

启动main函数,输出的结果是:

1

3

 1

 3 

这个应该是没有什么问题,没有涉及到静态变量,顺势而为,所以还是比较好理解的.在堆中申明变量地址,再给变量赋值。

 

再看代码二和输出:

public class Test {
    private static Test tester=new Test(); //启动 step three
    private static int count1;
    private static int count2=2; //启动 step three
    {
        count1++; //启动 step one
        count2++;
        System.out.println(""+count1);
        System.out.println(""+count2);
    }
    static{
        count1++;  //启动 step four
        count2++;
        System.out.println(""+count1);
        System.out.println(""+count2);
    }
    public Test(){
        count1++;  //启动 step two
        count2++;
        System.out.println(""+count1);
        System.out.println(""+count2);
    }
    public static Test getTester(){
        return tester; //启动 step five
    }
    public static void main(String[] args) {
        getTester(); //启动 step six
        System.out.println(""+count1);
        System.out.println(""+count2);
    }

}

启动main函数,输出结果如下:

1
1
2
2
3
3
3
3

从这个输出结果可以得出: JVM 在对static变量内存分配的时候,它针对类的处理顺序是:

类{}块——>类构造函数——>static 块——>再是方法块 .

通过这个实例,可以进一步认识到JVM 对static变量以及static 块再内存处理上的顺序,进而可以在实际的代码使用中,做到对static变量的规范合理使用。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值