user3147619
user3147619

Reputation: 147

Why is the reference passing in this code not working?

this is driving me crazy because it makes no sense.

In the following program, the b variable is not correctly set. b is supposed to be passed by copy, but because b is a reference to an object, this should work correctly, but it doesn't.

public class A {
private B b;

public void foo() {
    System.out.println("the value of b is : " + b);
    bar(b);
    System.out.println(b.getName());
}

private void bar(B b){
    if (b == null) b = new B();
    b.setName("me");
}

public class B {
private String name;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}
}


public class MainTest {
public static void main(String args[]) {
    A a = new A();
    a.foo();
}
}

After execution I get this error:

the value of b is : null
Exception in thread "main" java.lang.NullPointerException
at test.A.foo(A.java:12)
at test.MainTest.main(MainTest.java:6)

Upvotes: 0

Views: 45

Answers (2)

Eran
Eran

Reputation: 393771

When you pass a reference to a method, you are passing a copy of that reference. Therefore, if the reference is to a mutable object, the method can mutate that object. However, if you change the reference within the method, the caller won't see this change.

private void bar(B b){
    if (b == null) b = new B(); // this cannot change the reference passed by the caller
    b.setName("me"); // this can update an instance of B passed from the outside
}

For this method to work a expected, you should either make sure you never pass it a null reference, or you should return the newly created/modified instance :

private B bar(B b) {
    if (b == null) b = new B(); 
    b.setName ("me");
    return b;
}

and then assign the returned reference to the original variable :

b  = bar(b);

Upvotes: 1

TheLostMind
TheLostMind

Reputation: 36304

Yes.. NPE is expected here because of if (b == null) b = new B();. If you work on the orginal reference passed to bar(), its fine. The moment you do new B(), you are no longer working with the original reference.

You cannot reassign the reference to a different object. If you do, then the changes made using the new object will not be reflected in the original one.

Upvotes: 0

Related Questions