嗨我正在学习我的scja考试,并有一个关于字符串传递ref /值以及它们如何不可变的问题.以下代码输出"abc abcfg".
我想知道的是为什么会发生这种情况?我不明白方法f里面发生了什么.字符串是按值传递的,所以它肯定会在方法中变为"abcde"吗?因为如果b + ="fg"附加到字符串,为什么它在方法内部不起作用?
谢谢!
public class Test {
public static void main(String[] args){
String a =new String("abc");
String b = a;
f(b);
b+="fg"
System.out.println(a + " " + b);
}
public static void f(String b){
b+="de";
b=null;
}
}
Run Code Online (Sandbox Code Playgroud)
该生产线b+="de";的void f(String b)功能,创建一个完全新的对象String,不影响对象的main功能.
所以,当我们说String是一成不变的,当是指任何一个上改变String的对象将导致创建一个全新的String对象
public class Test {
public static void main(String[] args){
String a =new String("abc");
String b = a; // both a & b points to the same memory address
f(b); // has no effect
// b still has the value of "abc"
b+="fg" // a new String object that points to different location than "a"
System.out.println(a + " " + b); // should print "abc abcfg"
}
public static void f(String b){
b+="de"; // creates a new object that does not affect "b" variable in main
b=null;
}
}
Run Code Online (Sandbox Code Playgroud)
在您的方法中,f()您将一个新的字符串分配给参数b,但参数就像局部变量一样,因此向它们分配某些内容不会对方法之外的任何内容产生影响。这就是为什么您传入的字符串在方法调用后没有改变。
| 归档时间: |
|
| 查看次数: |
11694 次 |
| 最近记录: |