Java堆、栈和常量池

发表于:2010-4-16 10:15  作者:longxiaoyan(JavaEye)   来源:51Testing软件测试网采编

字体: | 上一篇 | 下一篇 |我要投稿 | 推荐标签:

class BirthDate {  
    private int day;  
    private int month;  
    private int year;      
    public BirthDate(int d, int m, int y) {  
        day = d;   
        month = m;   
        year = y;  
    }  
    省略get,set方法………  
}  
 
public class Test{  
    public static void main(String args[]){  
int date = 9;  
        Test test = new Test();        
           test.change(date);   
        BirthDate d1= new BirthDate(7,7,1970);         
    }    
 
    public void change1(int i){  
        i = 1234;  
    } 

class BirthDate {
    private int day;
    private int month;
    private int year;   
    public BirthDate(int d, int m, int y) {
        day = d;
        month = m;
        year = y;
    }
    省略get,set方法………
}

public class Test{
    public static void main(String args[]){
int date = 9;
        Test test = new Test();     
     test.change(date);
        BirthDate d1= new BirthDate(7,7,1970);      
    } 

    public void change1(int i){
     i = 1234;
    }
}

  对于以上这段代码,date为局部变量,i,d,m,y都是形参为局部变量,day,month,year为成员变量。下面分析一下代码执行时候的变化:

  1. main方法开始执行:int date = 9;
  date局部变量,基础类型,引用和值都存在栈中。
  2. Test test = new Test();
  test为对象引用,存在栈中,对象(new Test())存在堆中。
  3. test.change(date);
  i为局部变量,引用和值存在栈中。当方法change执行完成后,i就会从栈中消失。
  4. BirthDate d1= new BirthDate(7,7,1970);
  d1为对象引用,存在栈中,对象(new BirthDate())存在堆中,其中d,m,y为局部变量存储在栈中,且它们的类型为基础类型,因此它们的数据也存储在栈中。day,month,year为成员变量,它们存储在堆中(new BirthDate()里面)。当BirthDate构造方法执行完之后,d,m,y将从栈中消失。
  5. main方法执行完之后,date变量,test,d1引用将从栈中消失,new Test(),new BirthDate()将等待垃圾回收。


22/2<12

评 论

论坛新帖



建议使用IE 6.0以上浏览器,800×600以上分辨率,法律顾问:上海漕溪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2022, 沪ICP备05003035号
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪公网安备 31010102002173号

51Testing官方微信

51Testing官方微博

扫一扫 测试知识全知道