Why null assignment doesn't work in function

I tried 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 get the following output:

 [100,89] [89] [89] 

My question is why can't I assign the list as null inside the function being called?

+6
source share
3 answers

Since all method calls in java are passed by value, which means that the link was copied when another function was called, but they point to the same object.

Two reference copies pointing to the same object.

Another example might 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 snippet above does not affect the old object or its link at all.

+5
source

Links, such as plain old data types, are passed by value to functions in Java

update2 just makes the local parameter list null reference. It does not change the fact that list refers to the caller for this function.

So update2 is non-op.

update1 modifies the list through the link passed to this function.

+1
source

For more information, you can also try this way.

 List<Integer> list = new ArrayList<>(); public void test() { list.add(100); list.add(89); System.out.println(list); update1(list); System.out.println(list); update2(list); System.out.println(list+"not null"); } public void update1(List<Integer> list) { list.remove(0); } public void update2(List<Integer> list) { this.list = null; } 

Using this keyword update2 () sets the list as null.

Here is the conclusion.

[100, 89]

[89]

null now it will be null

0
source

All Articles