0

I suppose this code prints 512, but it prints 100. I think f = new Foo(512); change the reference of f from new Foo(100) to new Foo(512); then int num should be initialized as 512. But it doesn't. Is there any my misunderstanding regarding this code?

class Foo{
  private int num;
  public Foo(int n){
    num =n;
  }
  public void setNum(int n){
    num = n;
  }
  public int getNum(){
    return num;
  }
}
public class Bar{
  static void changeFoo(Foo f){
    f = new Foo(512);
  }
  public static void main(String[] args){
    Foo f = new Foo(100);
    changeFoo(f);
    System.out.println("f is " + f.getNum());
  }
}
Ezerk
  • 29
  • 6
  • 1
    java is completly `pass-by-value` and not `pass-by-reference`, that´s the missunderung you do have. – SomeJavaGuy Mar 21 '16 at 14:44
  • 1
    By the way, you can simplify this code since your class `Foo` is, essentially, the same as `java.lang.Integer` (especially since your `setNum()` method is never called) – dsh Mar 21 '16 at 14:48
  • Thank you, it seems the pass by reference works here – Ezerk Mar 21 '16 at 15:24

1 Answers1

3

You can't modify the caller's reference without returning a Foo and assigning it to the reference. Like,

static Foo changeFoo(Foo f){
    return new Foo(512);
}
public static void main(String[] args){
    Foo f = new Foo(100);
    f = changeFoo(f);
    System.out.println("f is " + f.getNum());
}

Or, assigning the field through the reference from the caller, like

 static void changeFoo(Foo f){
    f.num = 512; // <-- assuming your num field is named num.
 }

or

static void changeFoo(Foo f){
    f.setNum(512);
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • Thanks your help. It does change the Foo reference. Then, Why we can't change the caller's reference in the void method like my code? I can't figure out clear reason. – Ezerk Mar 21 '16 at 14:59