Java - it's like going with me

Possible duplicate:
Does Java follow the link?

So, consider the following two examples and their corresponding 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 will it be www.yahoo.com? This is not like a passbyvalue for me.

+4
source share
5 answers

the link is passed by value. But the new link still points to the same source object. Therefore you change it. In the first Integer example, you change the object referenced by breakpoints. Thus, the source file is not changed.

+10
source

Your first example:

 num = 2 

Same as

 num = new Integer(2) 

So, you see how this is not quite the same as your second example. If Integer allows you to set a value in it, you could do:

 num.setValue(2) // I know Integer doesn't allow this, but imagine it did. 

who would do exactly what the second example did.

+2
source

This value is pass-by-value, but the value is a reference to properties, and you do not change it, but only its internal field.

In the first case, you change the link, not some link element, and in the second you change the link element, but leave the link as it is.

+1
source

Try the following:

  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 = new Properties(); properties2.setProperty("url", "www.yahoo.com"); } } 

He prints "www.google.com".

In fact, you pass the value of the link, so the changes made to the object through this link will be visible. However, if you assign a new object reference for this parameter, this change will not be reflected, since you only passed the value of the link, not the actual reference to the variable.

+1
source

This is because properties2 is nothing more than a reference to an object. This means that the links passed to the method are actually copies of the original links. As shown in the illustration,

enter image description here

0
source

All Articles