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);
}
}
A newbie question.
Can someone explain why s1 is not getting updated to "this is a test" ?.
I thought in Java, object arguments are passed as references and if that is the case, then I am passing String s1
object as reference in Line 1.
And s1
should have been set to "this is a test" via display()
method.. Right ?
Java is pass-by-value always. For reference types, it passes a copy of the value of the reference.
In your
static String display(String s)
{
s = "this is a test";
return s;
}
The String s
reference is reassigned, its value is changed. The called code won't see this change because the value was a copy.
With String
s, it's hard to show behavior because they are immutable but take for example
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;
}
However, if you had
public static void doFoo(Foo some) {
some = new Foo();
some.foo = 19;
}
the original would still show 3
, because you aren't accessing the object through the reference you passed, you are accessing it through the new
reference.
Of course you can always return the new reference and assign it to some variable, perhaps even the same one you passed to the method.
String
is a reference which is passed by value. You can change where the reference points but not the caller's copy. If the object were mutable you could change it's content.
In short, Java ALWAYS passed by VALUE, it never did anything else.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With