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?
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.
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.
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.
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.
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).
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