简体   繁体   中英

Java. Argument does not change

static void f(String s)
{
    s = "x";
}

public static void main(String[] args) {
  String s = null;
  f(s);
}

Why the value of s after calling f(s) is null instead of "x"?

Because s is a reference. You pass a copy of that reference to the method, and then modify that copy inside the method. The original doesn't change.

When passing an Object variable to a function in java, it is passed by reference. If you assign a new value to the object in the function, then you overwrite the passed in reference without modifying the value seen by any calling code which still holds the original reference.

However, if you do the following then the value will be updated:

public class StringRef
{
  public String someString;
}

static void f(StringRef s)
{
  s.someString = "x";
}

public static void main(String[] args)
{
  StringRef ref = new StringRef;
  ref.someString = s;
  f(ref);
  // someString will be "x" here.
}

Within the function f() the value will be "x". Outside of this function the value of s will be null. Reference data types (such as objects) are passed by value see here (read the section "Passing Reference Data Type Arguments")

Given that s is of type String , which is a reference type (not a primitive):

s = "x";

does not mean "transform the thing that s refers to into the value "x" ". (In a language where null is a possibility, it can't really do that anyway, because there is no actual "thing that s refers to" to transform.)

It actually means "cause s to stop referring to the thing it currently refers to, and start referring to the value "x" ".

The name s in f() is local to f() , so once the function returns, that name is irrelevant; the name s in main() is a different name, and is still a null reference.

The only thing that the parameter passing accomplishes is to cause s in f() to start out as null .

This explanation would actually go somewhat more smoothly if you hadn't used null :(

Actually you are not changing the value you are creating new one, it is totally different, If you change an attribute of the abject in the method then i will be changed in your references. But you are creating new object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM