Ufx
Ufx

Reputation: 2695

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"?

Upvotes: 1

Views: 750

Answers (5)

Elbek
Elbek

Reputation: 3484

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.

Upvotes: 0

Karl Knechtel
Karl Knechtel

Reputation: 61537

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 :(

Upvotes: 0

Trevor Freeman
Trevor Freeman

Reputation: 7232

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.
}

Upvotes: 2

cyber-monk
cyber-monk

Reputation: 5560

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")

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272557

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.

Upvotes: 5

Related Questions