Possible Duplicate:
Is Java pass by reference?
How come this code of mine is not working? I am passing an object into a method but it won't modify the original object that I created in main, why is that?
public class TestRun{
public static void main(String[] args){
Test t1 = new Test();
Test t2 = new Test();
t2.x = 555;
t2.y = 333;
System.out.println("The original valuess of X and Y are");
System.out.println("X = "+t1.x+"Y = "+t1.y);
modifyObject(t1,t2);
System.out.println(开发者_如何学Go"After the modification ");
System.out.println("X = "+t1.x+"Y = "+t1.y);
}
public static void modifyObject(Test arg1,Test arg2){
arg1 = arg2;
}
}
public class Test{
int x = 9999;
int y = 1;
}
You answered it in the title. Java is "pass by value".
This means that the method receives only copies of the object references arg1
and arg2
.
You can, however, alter the contents of the objects, by doing
arg1.x=arg2.x
ary1.y=arg2.y
Its pass by value yes.
But what you need to recognise is that Test are reference types. In C, they would be pointers.
So what you're in fact doing in when calling modifyObject(arg1,arg2) is copying the values of the pointers (i.e. copying the memory address of the pointer, or copying the value of the variable with is the reference).
in function modifyObject:
arg1 receives an address of an object of type Test, let's say x1000 arg2 receives another address of an object, let's say x2000
arg1 contains a reference to an object, but if you do arg1 = arg2, you are just telling arg1 to point to another address.
this way, you are not touching the content of the object pointed by arg1
arg1 and arg2 are local variables in the function. to make changes to the object, you need to address to the memory where it is stored, but arg1.x or arg1.y
notice that the object is somewhere in the memory, and arg1/arg2/t1/t2 are just saying where they are located, they are not the "actual" objects
Uh?!!
What was your expectations? So, you create and print object t1
whose x,y
values are 999,1
respectively. If you print it, that's what you'll get
$ java TestRun
The original valuess of X and Y are
X = 9999, Y = 1
After the modification
X = 9999, Y = 1
So... what is your question again?
- Q Is Java pass by value? A: Yes
- Q It won't modify the original object? A: That's correct, it won't be modified.
- Q Why is that? A: Because Java is pass by value
精彩评论