Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java- passing Lists to methods working as pass by reference

Tags:

java

There are lot of discussions in stackoverflow regarding pass by value and pass by reference. But i want to know what is happening in the following scenario? This page says java is pass by value. Is Java "pass-by-reference" or "pass-by-value"?.

In case of following code, the the element is removed from the removeElement method , it is removing the 5th element from list when i print the list.

public class Load {
    public static void main(String[] args) {


        ArrayList<Integer> list = new ArrayList<Integer>();
        list.addAll(Arrays.asList(1,1,2,3,5,5,13,21));
        removeElement(list);
        System.out.println(list);
    }
        public static void removeElement(List<Integer> list){
            list.remove(5);//removes element at index 5
        }
}

The output of the program is [1, 1, 2, 3, 5, 13, 21].

Can somebody explain how this is pass by value rather than pass by reference?

like image 205
alekya reddy Avatar asked Apr 19 '15 06:04

alekya reddy


People also ask

Can we pass List as reference in Java?

Yes, a List that you pass to a method is passed by reference. Any objects you add to the List inside the method will still be in the List after the method returns. Save this answer.

Is Java List pass by value or reference?

Java is always Pass by Value and not pass by reference, we can prove it with a simple example. Let's say we have a class Balloon like below. And we have a simple program with a generic method to swap two objects, the class looks like below.

How do you pass a List to another method in Java?

In case of primitives it purely pass by value and in case of Objects it is pass by value of the reference . When you pass list from the main method to method removeElement() as an argument there is another (copy) reference that is created that points to the same List instance.

How can we pass argument to the method by reference?

C/C++ supports the call by reference because in the call by reference we pass the address of actual parameters in the place of formal parameters using Pointers.


1 Answers

Java is always pass by value. The value of any variable of type Object is actually a reference. That's why, for example, == is said to be a reference comparison, and you need to use .equals() for comparing Object(s).

like image 144
Elliott Frisch Avatar answered Sep 28 '22 09:09

Elliott Frisch