Possible Duplicate:
Is Java pass by reference?
So consider the following two examples and their respective output:
public class LooksLikePassByValue {
public static void main(String[] args) {
Integer num = 1;
change(num);
System.out.println(num);
}
public static void change(Integer num)
{
num = 2;
}
}
Output:
1
public class LooksLikePassByReference {
public static void main(String[] args) {
Properties properties = new Properties();
properties.setProperty("url", "www.google.com");
change(properties);
System.out.println(properties.getProperty("url"));
}
public static void change(Properties properties2)
{
properties2.setProperty("url", "www.yahoo.com");
}
}
Output:
www.yahoo.com
Why would this be www.yahoo.com?
This doesn't look like passbyvalue to me.
The reference is passed by value. But the new reference is still pointing to the same original object. So you modify it. In your first example with the Integer
you are changing the object to which the reference points. So the original one is not modified.
Your first example does:
num = 2
That is the same as
num = new Integer(2)
So you see how it is not quite the same as your second example. If Integer let you set the value in it, you could have done:
num.setValue(2) // I know Integer doesn't allow this, but imagine it did.
which would have done exactly what the second example did.
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