先上结论:
基本类型的赋值都是直接赋予相同的值,而引用类型的赋值赋予的只是其内存的引用。
如果a=b,若b是基本类型,则赋值操作将b的值复制一份传给a,此后a的值改变完全不影响b。
若b是引用类型,赋值操作将b引用赋予了a,此时两者指向堆中的同一个对象(b指向的对象),而a原先引用的对象会被垃圾回收机制清理。
public class ObjectAssignment {
public static void main(String[] args) {
//基本类型赋值:
char a = 'A';
char b = 'B';
System.out.println("a的值为"+a+",b的值为"+b);
a=b;
a = 'C';
System.out.println("a的值为"+a+",b的值为"+b);
//引用类型赋值
ReferenceType type1 = new ReferenceType();
ReferenceType type2 = new ReferenceType();
type1.ref=10;
type2.ref=20;
System.out.println("type1.ref的值为"+type1.ref+",type2.ref的值为"+type2.ref);
type1=type2;
System.out.println("type1.ref的值为"+type1.ref+",type2.ref的值为"+type2.ref);
type1.ref=100;
System.out.println("type1.ref的值为"+type1.ref+",type2.ref的值为"+type2.ref);
}
}
class ReferenceType{
int ref;
}
代码输出结果为:
a的值为A,b的值为B
a的值为C,b的值为B
type1.ref的值为10,type2.ref的值为20
type1.ref的值为20,type2.ref的值为20
type1.ref的值为100,type2.ref的值为100
基本类型赋值的部分很好理解。
引用部分的赋值分析:
这是一个简单的ReferenceType类,在main()方法创建了两个实例对象。两个对象的ref属性分别被赋予不同的值。然后,ref2的值被赋予ref1。由于java中引用对象的赋值操作只是操作其引用,因此此时ref2与ref1的引用指向堆中的同一个对象type2(type1原始对象的引用在type2赋值给它时丢失,它引用的对象会在垃圾回收时被清理)。而后改变了type2.ref的值就也同时改变了type1.ref的值,这种现象通常称为别名(alaising),这是java处理对象的一种基本方式。