0

I have the following

class Test{

    public Inner x;

    public static void main(String[] args){

        Test t = new Test();
        t.bar(t.x);

    }

    public Test(){
        x = new Inner();
        System.out.println("X = "+x.val);
    }

    public void bar(Inner a){
        x.val = 2;
        System.out.println("a = "+a.val);
        a = new Inner(5);
        System.out.println("a = "+a.val);
        System.out.println("X = "+this.x.val);
    }

    class Inner{
        public int val;
        public Inner(){val=0;}
        public Inner(int i){val=i;}
    }
}

I am concerned why the program tells me that my class's inner object and passed-in object are the same, but when I change the passed object to a new one, they are suddenly not the same. I thought java passed by pointers, and thus changing the pointer location of "a" in my bar method would likewise change the pointer location of "x", which was passed in.

  • Passing by pointers is different from passing by reference. Changing a pointer to point somewhere else does not change other pointers to also point there. – Thilo Mar 07 '16 at 04:07
  • So how can I achieve the desired effect in this program? Which is passing in an object variable and changing it inside the method? – user6027364 Mar 07 '16 at 04:13
  • You can't pass arguments by reference in Java. If you want to change `x` from within `bar()`, you can just set `x = new Inner(5);`. If that's not an option, you'll have to use a mutable wrapper class. – shmosel Mar 07 '16 at 04:20
  • Ok, I see what you're saying. Can you expound on how to use a mutable wrapper class? Or is there a good web resource that explains it well? – user6027364 Mar 07 '16 at 04:24

3 Answers3

0

Do you want to change by "a", to change the "x" it? Keyword "new" will open up a new memory, so the function "bar" inside your "x" and "a" is a pointer to a different memory, you modify the "a" will not change "x". You can try to modify the "bar" as follows:

 public void bar(Inner a){
    x.val = 2;
    System.out.println("a = "+a.val);
    //a = new Inner(5);
    a.val = 5;
    System.out.println("a = "+a.val);
    System.out.println("X = "+this.x.val);
}
east_R
  • 1
0

You are creating a totally new object when you do a = new Inner(5);

ΦXocę 웃 Пepeúpa ツ
  • 43,054
  • 16
  • 58
  • 83
0

In Java, it is always 'pass by value' and not pass by reference. When you pass t.x to your bar method, copy of memory address is created and it is passed to method. Suppose you change a = null in your bar method, this will not make your t.x to null as only a reference variable is set to null in your method.

a = new Inner(5);

This line reassigning your reference variable to new memory location which is different from t.x. Hence any change to this memory location will not any impact to t.x.

Bhushan
  • 537
  • 1
  • 5
  • 14