pointers - Java Object assignment when passing to a method -


this question has answer here:

i have 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);         = 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 concerned why program tells me class's inner object , passed-in object same, when change passed object new one, not same. thought java passed pointers, , changing pointer location of "a" in bar method likewise change pointer location of "x", passed in.

do want change "a", change "x" it? keyword "new" open new memory, function "bar" inside "x" , "a" pointer different memory, modify "a" not change "x". can try modify "bar" 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); } 

Comments

Popular posts from this blog

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

reactjs - React router and this.props.children - how to pass state to this.props.children -

Excel VBA "Microsoft Windows Common Controls 6.0 (SP6)" Location Changes -