将String对象作为参数传递Java

Und*_*Dog 3 java

class prog {

      static String display(String s)
      {
         s = "this is a test";
         return s;
      }

   public static void main(String...args) {

     prog p = new prog();
     String s1 = "another";
     System.out.println(display(s1)); //Line 1
     System.out.println(s1);
   }
}
Run Code Online (Sandbox Code Playgroud)

一个新手问题.

有人能解释为什么s1没有更新到"这是一个测试"吗?

我认为在Java中,对象参数作为引用传递,如果是这种情况,那么我将String s1对象作为引用传递给第1行.

并且s1应该通过display()方法设置为"这是一个测试" .对吗?

Sot*_*lis 15

Java总是以值传递.对于引用类型,它传递引用值的副本.

在你的

static String display(String s)
{
    s = "this is a test";
    return s;    
}
Run Code Online (Sandbox Code Playgroud)

String s参考被重新分配,则其值被改变.被调用的代码不会看到此更改,因为该值是副本.

使用Strings,很难显示行为,因为它们是不可变的但是以此为例

public class Foo {
    int foo;
}

public static void main(String[] args) {
    Foo f = new Foo();
    f.foo = 3;
    doFoo(f);
    System.out.println(f.foo); // prints 19
}

public static void doFoo(Foo some) {
    some.foo = 19;
}
Run Code Online (Sandbox Code Playgroud)

但是,如果你有

public static void doFoo(Foo some) {
    some = new Foo();
    some.foo = 19;
}
Run Code Online (Sandbox Code Playgroud)

原始文件仍会显示3,因为您没有通过您传递的引用访问该对象,而是通过new引用访问它.


当然,您始终可以返回新引用并将其分配给某个变量,甚至可能是您传递给方法的变量.