0

In the code below why foo2 is null when printing its data at system.out.print?

public class Helper {
    public void shadowCopy(Foo foo1, Foo foo2){
        foo2 = foo1;
    }

    public static void main(String[] args) {
        Helper h = new Helper();
        Foo foo1 = new Foo(50);
        Foo foo2= null;
        h.shadowCopy(foo1, foo2);
     System.out.println(foo2.data);// why  java.lang.NullPointerException?
    }

    public static class Foo {

        public int data=0;
        public Foo(int data){
            this.data = data;
        }
    }

}
C graphics
  • 7,308
  • 19
  • 83
  • 134

2 Answers2

2

In shadowCopy, foo2 is a copied reference to the same object that foo2 in main is referring to. However, it assigns only its local foo2 reference to refer to the same object as foo1. It doesn't change the foo2 reference variable in main, which remains null. That leads to the NPE.

To get the desired behavior, just place foo2 = foo1; in main, so you're not dealing with copies of reference variables.

rgettman
  • 176,041
  • 30
  • 275
  • 357
0

Well, because foo2 is null in the main method, and you're trying to access its data field.

References are passed by value, so shadowCopy() assigns a copy of a reference to foo1 to a copy of a reference to foo2. The value of foo2 in main stays unmodified.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255