gpt4 book ai didi

java - java中的值传递和引用传递

转载 作者:行者123 更新时间:2023-12-01 06:33:21 26 4
gpt4 key购买 nike

我正在阅读有关java中的按值传递和按引用传递的文章,其中一些说Java仅遵循“按值传递”,其中一些说原语和对象之间存在一些差异。所以我写了以下示例代码。并输出也。请评论并分享确切的答案是什么。

我检查了 Int、String、StringBuffer 和 Employee 类,现在它仅作为 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

最佳答案

Java 仅支持值传递。

但是,对于对象来说,按值传递的是对象的引用。。不,这与引用传递不同。区别在于:

如果你这样做:

public void doChange(Emp i) {
i = new Emp("changed!", 42);
}

它在方法外部绝对没有影响 - 因为引用i是方法外部使用的引用的副本。但是,它引用同一个对象,因此如果您使用引用来更改对象的字段,这些更改在方法外部是可见的。

关于java - java中的值传递和引用传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9109529/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com