Reputation: 210
What is the difference between following code in Java? I couldn't clearly catch out how objects are passed in Java. Can anyone explain the code below.
package cc;
public class C {
public static class Value {
private String value;
public void setValue(String str) {
value=str;
}
public String getValue() {
return value;
}
}
public static void test(Value str) {
str.setValue("test");
}
public static void test2(Value str) {
str=new Value();
str.setValue("test2");
}
public static void main(String[] args) {
String m="main";
Value v=new Value();
v.setValue(m);
System.out.println(v.getValue()); // prints main fine
test(v);
System.out.println(v.getValue()); // prints 'test' fine
test2(v);
System.out.println(v.getValue()); // prints 'test' again after assigning to test2 in function why?
}
}
Upvotes: 0
Views: 1606
Reputation: 5946
in java, object is passed by value. it copies the reference of v2 to str. Although you create a new object and assigned to str, str is local variable within test2 method scope. Only str inside test2 method is changed.
public static void test2(Value str) {
str=new Value();
str.setValue("test2");
System.out.println(str.getValue());
}
Upvotes: 0
Reputation: 20264
When you pass v
into test2
what you are actually doing is passing a copy of the reference that points to v
into the method - think of it as a new variable which has the same value as v
.
When you assign a new Value
object to str
inside test2
you are assigning a new value to the copy of the reference - your original reference, which exists inside main
is unaffected by this reassignment, and still refers to the original object.
When you execute your third println
in main
you are still using the original Value
object, not the new one that was created inside test2
, and so you see test
and not test2
printed out.
Upvotes: 1
Reputation: 240996
In test2()
a new instance is created and you are setting value in newer instance, and not in the Object whose reference is passed
public static void test2(Value str) {
str=new Value();
str.setValue("test2");
}
See Also
Upvotes: 3