gpt4 book ai didi

java - 使用 void 方法修改对象或基元

转载 作者:行者123 更新时间:2023-12-01 18:38:00 24 4
gpt4 key购买 nike

考虑以下代码中的第 2 行和第 3 行......

class ModifyObjects {
static void modifyString1(String s){
s = "xyz";
//Or any other operations
}

static String modifyString2(String s){
s = "xyz";
return s;
//Or any other operations
}

static void modifyPrimitive1(int i){
i=9;
}

static int modifyPrimitive2(int i){
i=9;
return i;
}
}

public class Operations {

public static void main(String[] args) {
// TODO Auto-generated method stub

String st1 = "abcd";
String st2 = "qwerty";
String st3;

int i1=0, i2;

st1 = "xyz"; //line 1
System.out.println("st1: " + st1);

ModifyObjects.modifyString1(st2);
System.out.println("st2: " + st2); //line 2

st3 = ModifyObjects.modifyString2(st2);
System.out.println("st3: " + st3);

System.out.println("st2: " + st2);

ModifyObjects.modifyPrimitive1(i1);
System.out.println("i1: " + i1); //line 3

i2 = ModifyObjects.modifyPrimitive2(i1);
System.out.println("i2: " + i2);
}
}

第 2 行将 st2 指定为 qwerty(不修改。应该是 xyz。) 第 3 行给出 i1 = 0(不修改。应该是 9。)

这看起来有点奇怪。这是输出:

 st1: xyz
st2: qwerty
st3: xyz
st2: qwerty
i1: 0
i2: 9

还在第 1 行创建了一个新的字符串对象“xyz”,对吗?我认为“abcd”只是没有从这里被引用。

最佳答案

在 Java 中,对象的引用是按值传递的...

    1.  st1: xyz

Reason : you are not returning anything...

2. st2: qwerty

Reason :You are not storing the returned value in st2. you should do,

st2=ModifyObjects.modifyString1(st2);

3. st3: xyz

reason : You are returning a String value and storing it in st3

4. st2: qwerty

Reason : st2 is qwerty...

5. i1: 0 // Not reassigning value to anything

6. i2: 9 // returned value reassigned to i2.

关于java - 使用 void 方法修改对象或基元,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21014891/

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