Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why null assignment not working in a function [duplicate]

Tags:

java

list

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?

like image 915
Kajal Avatar asked Apr 07 '16 12:04

Kajal


1 Answers

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.

like image 65
Ahmed Hegazy Avatar answered Oct 30 '22 01:10

Ahmed Hegazy