在Java中,基本数据类型(byte, int, short, long, float, double, boolean, char)的变量存储在"栈"中,对象类型的变量则存储在"堆"中,而在"栈"中只是保留了引用的内存的地址.
结论:
基本类型的变量值存储在"栈"中.
对象类型的变量值存储在"堆"中
在"=="和"!="比较的是地址,或者说是对象的句柄,而equals()方法比较的是对象的内容.或者说"=="和"!="比较的是"栈"中的内容,而equals()比较的是"堆"中的内容.
变量复制的例子.
int x=0;
int y=x;
x=1;
System.out.println("y="+y);
结果为y=0;
class student
{
public String id;
public String name;
}
Student student1=new Student();
student1.id="0001";
student1.name="Tom";
Student student2=student1;
student1.id="0002";
student1.name="Jike";
System.out.println("student2.id="+student2.id);
System.out.println("student2.name="+student2.name);
结果为.student2.id=0002 student2.name=Jike
引用传递和值传递
基本类型采用值传递方式向方法传递参数.
对象类型采用引用传递方式向方法传递参数.
在Java中,参数传递时被传递的内容都是来自"栈"中,只是因为"栈"中保存的是基本类型的值本身,对象类型的内存地址,这才导致了值传递和引用传递这两种表现形式.
事实上在Java中值存在一种复制和传递手段-值传递,复制和传递的内容都是来自"栈"中数据的副本.
但是在变量复制时,String类型(在"栈"中保存的也是其内存地址)的情况比较特殊,它看起来更类似于基本类型;这一规律在变量传递时仍然成立.原因在于String类型自身在实现上的特殊性-针对String对象的每个赋值操作均会产生一个新的String对象.