Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - This seems like pass by reference to me [duplicate]

Tags:

java

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.

like image 600
Shawn Avatar asked Dec 10 '22 06:12

Shawn


2 Answers

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.

like image 153
Petar Minchev Avatar answered Dec 29 '22 10:12

Petar Minchev


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.

like image 32
shoebox639 Avatar answered Dec 29 '22 11:12

shoebox639