一
1.寄存器:最快的存储区, 由编译器根据需求进行分配,我们在程序中无法控制.
2. 栈:存放基本类型的变量数据和对象的引用,但对象本身不存放在栈中(String str = new String() , str(对象引用存在栈里) , new String()(对象存在堆里)).
3. 堆:存放所有new出来的对象。或者常量池中(字符串常量对象存放在常量池中。)
4. 静态域:存放静态成员(static 修饰的)
5. 常量池:存放字符串常量和基本类型常量(public static final)。
二
堆是私有的 ,栈是共有的,所以栈和常量池中的对象可以共享,堆中的对象不可以共享。 栈中的数据大小和生命周期是可以确定的,当没有引用指向数据时,这个数据就会消失。堆中的对象的由垃圾回收器(GC)负责回收,因此大小和生命周期不需要确定,具有很大的灵活性。
对于字符串:其对象引用(str)都存储在栈中的,如果是编译期已经创建好(直接用双引号定义的 String = ““aa”” (String对象是不可变的))的就存储在常量池中,如果是运行期(new出来的 String str = new String() )就存储在堆中。对于equals相等的字符串,在常量池中永远只有一份,在堆中有多份。
三.字符串
String str1 = "aaa";
String str2 = "aaa";
String str3 = "aaa";
String ss1 = new String("aaa");
String ss2 = new String("aaa");
String ss3 = new String("aaa");
这里说一下红色这3个箭头,对于通过new产生一个字符串(假设为”aaa”)时,会先去常量池中查找是否已经有了”aaa”对象,如果没有则在常量池中创建一个此字符串对象,然后堆中再创建一个常量池中此”aaa”对象的拷贝对象。有道面试题:String s = new String(“aaa”);产生几个对象?,如果常量池中原来没有”aaa”,就是两个。
四.程序内存图
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存储在test中, new Test()存储在堆内存中
3. test.change(date); 新开一个栈,i为局部变量存储在栈里,该方法走完,该栈消失,i也随之消失,
4. BirthDate d1= new BirthDate(7,7,1970); 对象引用d1存储在栈中, new BirthDate(7,7,1970); 存储在堆中,其中d,m,y为局部变量存储在栈中,且它们的类型为基础类型,因此它们的数据也存储在栈中。day,month,year为成员变量,它们存储在堆中(new BirthDate()里面)。当BirthDate构造方法执行完之后,d,m,y将从栈中消失。
5.main方法执行完之后,date变量,test,d1引用将从栈中消失,new Test(),new BirthDate()将等待垃圾回收。