0

Can someone please explain the output of the below code. Why is line 5 not printing null but line 8 printing the updated values from changeValue method. I saw many posts about pass by value but they don't give details about the assigning the "null" reference.

public class ObjectPassbyvalueTest {
public static void main(String[] args) {
    Student s = new Student("A");
    change(s);
    System.out.println(s); // Why is this printing the Student Object and
                            // not null?

    changeValue(s);
    System.out.println(s); // This is printing the updated Student Object
                            // with name "B"
}

public static void change(Student s) {
    s = null;
}

public static void changeValue(Student s) {
    s.name = "B";
}

}

class Student {
String name;

public Student(String name) {
    super();
    this.name = name;
}

@Override
public String toString() {
    return "Student [name=" + name + "]";
}

}

Output: Student [name=A] Student [name=B]

user2186831
  • 355
  • 2
  • 10
  • It doesn't matter whether you write `s = new Student();` or `s = null;` within the `change()` method - both statements change the local reference `s` but that change doesn't propagate to the caller. – Thomas Kläger Jan 18 '23 at 13:52
  • @ThomasKläger Then how come the change in `changeValue()` method propagated to the caller. There also, the local variable s is only changed right. I am missing something. Can you help me understand please. – user2186831 Jan 18 '23 at 14:19
  • In the `changeValue` method you modify the `Student` referenced by `s`. Both the local variable `s` in the main method and the parameter `s` in the `changeValue` mthod reference the same `Student` object - but this is explained in the linked question https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value – Thomas Kläger Jan 18 '23 at 14:57

0 Answers0