java值传递

原文:http://www.programcreek.com/2011/08/so-java-passes-object-by-reference-or-by-value/


//注释处为个人见解。。。




This is a classic interview question which confuses novice Java developers. In this post I will use an example and some diagram to demonstrate that: Java is pass-by-value.

1. Some Definitions

Pass by value: make a copy in memory of the actual parameter’s value that is passed in.
Pass by reference: pass a copy of the address of the actual parameter.

Java is always pass-by-value. Primitive data types and object reference are just values.

//java总是值传递。。基本类型和obj都是值

2. Passing Primitive Type Variable

Since Java is pass-by-value, it’s not hard to understand the following code will not swap anything.

swap(Type arg1, Type arg2) {
    Type temp = arg1;
    arg1 = arg2;
    arg2 = temp;
}


3. Passing Object Variable

Java manipulates objects by reference, and all object variables are references. However, Java doesn’t pass method arguments by reference, but by value.

Question is: why the member value of the object can get changed?

java-pass-by-value

Code:

class Apple {
	public String color="red";
}
 
public class Main {
	public static void main(String[] args) {
		Apple apple = new Apple();
		System.out.println(apple.color);
 
		changeApple(apple);
		System.out.println(apple.color);
	}
 
	public static void changeApple(Apple apple){
		apple.color = "green";
	}
}


Since the orignal and copied reference refer the same object, the member value gets changed.

//java没有指针。。java obj对象都是在堆里产生。。栈里保存对其的引用。。这就象指针一样。。(仅仅像。。不=指针);

//java传递变量是永远都是值传递。。。对obj来说。。如上例。。传递的就是    一个指向Apple类型的引用变量。。的副本;如下图

Output:

red
green


//关于String:String是特殊的对象。。因为字符串是不可变的。。所以每次改变String类型变量时就相当于在堆内重新New了一个字符串。。。在把其引用丢给String变量。。



public static void main(String[] args) {  
    String a= new String("111");  
    change(a);  
    System.out.println(a);  
}  
   
public static void change(String a) {  
    a = "222";  
}  



//输出111;


//上文说java永远都是值传递。。

//so。。上面例子中传递的就是a的一个副本。。如下图


//调用方法时。。复制了一份引用变量a。。传递给change方法。。然后chuange方法new了一个字符串"222",再把其引用丢给a副本;

//TIP:如果本例为StringBuilder结果为222   

public static void main(String[] args) {  
	    StringBuilder a= new StringBuilder("111");  
	    change(a);  
	    System.out.println(a);  
	}  
	   
	public static void change(StringBuilder a) {  
	    a.append("222");  
	}  



//因为a和a副本都引用堆中同一份的   111,so输出为  111222;

//写完收工。。。。。。。。。。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值