I was trying the following code,
public void test() {
List<Integer> list = new ArrayList<>();
list.add(100);
list.add(89);
System.out.println(list);
update1(list);
System.out.println(list);
update2(list);
System.out.println(list);
}
public void update1(List<Integer> list) {
list.remove(0);
}
public void update2(List<Integer> list) {
list = null;
}
I am getting the following output,
[100,89]
[89]
[89]
My question is, why I am not able to assign the list as null inside a called function?
Because all method calls in java are pass by value and that means that the reference got copied when you call another function, but the two are pointing to the same object.
Two reference copies pointing to the same object.
Another Example would be
public void update2(List<Integer> list) {
list = new ArrayList<>(); // The new refrence got assigned to a new object
list.add(23); // Add 23 to the new list
}
This above snippet don't affect the old object or it's reference at all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With