1
class OpenSource {
    private int x;

    public OpenSource(int x) {
        this.x = x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getX() {
        return x;
    }

    static OpenSource Open(OpenSource opensource) {
        opensource = new OpenSource(100);    //line 19
        return opensource;
    }

    public static void main(String a[]) {
        OpenSource open = new OpenSource(300);    //line 24
        System.out.println(open.getX() + ".");
        OpenSource opensource = Open(open);       //line 26
        System.out.println(open.getX() + ".");
        System.out.println(opensource.getX() + ".");
        open = Open(opensource);
        System.out.println(open.getX() + ".");
        System.out.println(opensource.getX());

    }

}

//why the output produces 300 300 100 100 100 why not 300 100 100 100 100 where i am wrong? i have drawn representation as below to understand it. Problem 1

Prashant
  • 419
  • 6
  • 14

1 Answers1

0

Inside your function Open you have this line:

opensource = new OpenSource(100);    //line 19

But the opensource variable here is really just a copy of the location of the object that was passed. Changing the copy of the location doesn't change the location of the original, that's not something you can do in Java.

Let's look at this slightly simpler example:

public static Integer addOne(Integer in) {
    in = in + 1;
    return in;
}

// ... sometime later
Integer three = Integer.valueOf(3);
Integer four = addOne(three);

In this example, we expect the variable three to only ever hold the value 3, even though inside of addOne we modify the variable in, we're not updating the variable three, only updating a copy of the variable three, called in.

Mark Elliot
  • 75,278
  • 22
  • 140
  • 160