java基础之内存

来源:互联网 发布:网站关键词优化推广 编辑:程序博客网 时间:2024/05/17 09:13

1 内存划分

栈(stack):局部变量、对象声明的引用

堆(heep):new出来的类或数组的实例(含成员变量)

静态域:静态变量(用static修饰的变量)

常量池:字符串常量(用final修饰的)


2 内存图

Person类:public class Person{private String name;private int age;private static int legs = 2;public void setName(String n){this.name = n;}}main方法的代码:public static void main(String[] args){Person p1 = new Person();p1.setName(“zhangsan”);p1.setAge(20);System.out.println(p1);}

第一行代码:Personp1 = new Person();

Person p1:对象声明的引用,存放在栈内存。

new Person() new出来的实例,在堆内存中。调用Person类的无参构造函数。name初始值为null,age初始值为0


第二行代码:p1.setName(“zhangsan”);

调用类方法:

private void setName(String n){

         this.name= n;

}

n为局部变量,存放于栈内存。setName方法执行完后,n出栈

name类型为String类型的常量,存放于常量池


第三行代码:p1.setAge(20);

调用类方法:

private void setAge(int a){

         this.age= a;

}

a为局部变量,存放于栈内存。setAge方法执行完后,a出栈

a为基本数据类型,进行值传递


3 练习

class Value{int i = 15;}class Test{public static void main(String[] args){Test t = new Test();t.first();}public void first(){int i=5;Value v = new Value();v.i = 25;second(v,i);System.out.println(v.i);}public void second(Value v, int i){i = 0;v.i = 20;Value val = new Value();v = val;System.out.println(v.i + " " + i);}}

Test t = new Test();


t.first()

public void first(){

        int i=5;

        Value v = new Value();

        v.i = 25;

        second(v,i);

        System.out.println(v.i);

    }


second(v,i);

    public void second(Value v, int i){

        i = 0;

        v.i = 20;

        Value val = new Value();

        v = val;

        System.out.println(v.i +" " + i);

    }


System.out.println(v.i + " " + i);  //15 0

System.out.println(v.i);    // 20



原创粉丝点击