Possible Duplicate:
Is Java “pass-by-reference”?
I want to know how to pass an object as a parameter to a method by referance in java.
I tried this code
public class Class1
{
public Class1()
{
String x = null;
F(x);
//x = null
System.out.println("x = " + x);
}
void F(String x)
{
x = "new String";
}
public static void main(String[] args)
{
new Class1();
}
}
You can see that I pass a String to a function F and I change String’s value inside it, but I can’t see the changes I made on it outside the Function F. When I execute this code, I got //{x = null} which is not what I expected //{x = new String}.
The objects themselves are passed by reference, but that reference is passed by value.
What this means is that you can change the objects in your function, i.e. you can change their fields, call methods on the object that change it’s state, etc.
You’re trying to change the reference in your function. That reference is only a copy.
Also note that
Stringis an immutable type. So even with it’s reference, you can’t change the underlyingObject.