我正在閱讀關於通過值傳遞和在Java中通過引用傳遞,我收到了很多文章,其中一些人說Java只跟隨「按值傳遞」,其中一些說一些原始和對象之間的區別。所以我寫了下面的示例代碼。 並把輸出也。 請評論並共享究竟是什麼,答案是。在java中傳遞值和通過引用傳遞
我檢查了詮釋,字符串,StringBuffer的和Employee類,現在它的工作僅作爲員工類別的參考。
package test;
class Emp {
public String name="";
public int age=0;
public Emp(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String toString() {
return "Name: "+ this.name + "....Age: "+ this.age;
}
}
public class Class1 {
public Class1() {
super();
}
public void doChange(int i) {
i = i +10;
System.out.println("Value of Integer in Method:>"+ i);
}
public void doChange(Emp i) {
i.age=29;
i.name="rishu";
System.out.println("Value of Employee In Method "+i.toString());
}
public void doChange(String i) {
i = i + " Hello";
System.out.println("value of i->"+ i);
}
public static void main(String[] args) {
int i =10;
String str="XXX";
Class1 c= new Class1();
StringBuffer sb= new StringBuffer();
Emp e= new Emp("abhi",28);
sb.append("ABC ");
System.out.println("");
System.out.println("Value of Integer before Method:->"+ i);
c.doChange(i);
System.out.println("Value of Integer after Method:->"+ i);
System.out.println("");
System.out.println("Value of String before Method:->"+ str);
c.doChange(str);
System.out.println("Value of Integer after Method:->"+ str);
System.out.println("");
System.out.println("Value of StringBuffer before Method:->"+ sb);
c.doChange(sb.toString());
System.out.println("Value of StringBuffer after Method:->"+ sb);
System.out.println("");
System.out.println("Value of Employee before Method:->"+ e.toString());
c.doChange(e);
System.out.println("Value of Employee after Method:->"+ e.toString());
}
}
輸出:
Value of Integer before Method:->10
Value of Integer in Method:>20
Value of Integer after Method:->10
Value of String before Method:->XXX
value of i->XXX Hello
Value of Integer after Method:->XXX
Value of StringBuffer before Method:->ABC
value of i->ABC Hello
Value of StringBuffer after Method:->ABC
Value of Employee before Method:->Name: abhi....Age: 28
Value of Employee In Method Name: rishu....Age: 29
Value of Employee after Method:->Name: rishu....Age: 29
請參閱:http://stackoverflow.com/questions/40480/ is-java-pass-by-reference – 2012-02-02 09:05:23
這是'i.name =「rishu」'和'i = rishu'(或'i = new Emp(「rishu」,...)')之間的很大區別。第一個是改變'i'中的對象_saved_,第二個改變'i'本身。 – 2012-02-02 09:19:53