educative.io

Pass By Reference Question - Java Integer

I understand why there will be no swapping because what we swapped is the pointer.

However, as in the diagram below Q2, a and b point to the same objects as x and y, what if we just modify the value of a and b? Will this change the value of x and y?


I hope this diagram explains it. only copies a and b are changed from pointing to 5, 9 to 55, 99

image

Thanks, Viraj.

Java Integer is actually a wrapper class of a final int. So it’s immutable.
I mistook Integer and List for the same.

1 Like

@Ye_Shao it has nothing to do with immutability. It’s purely about references getting copied. References of mutable classes will be treated the same in the example you provided. You can test your assumption easily with different classes or write your own class.

@Viraj_Bhosle but why this same behavior not occur when we pass reference of list which has memory already acquired in heap

example →
In below code superList will have 1 added , as per my understanding because of pass by value object address is passed and on that address list is updated . But same not happens in case of wrapper class . This is explainable only as @Ye_Shao said wapper classes are immutable thus new
address is allotted every-time value is changed.

class SuperList {
public List sList;

public SuperList(int n) {
  List<Integer> superList = new ArrayList<Integer>();
  allocate(superList, n);
  sList = superList;
}

void allocate(List<Integer> list, int n) {
  
  
  list.add(1);
}

}

@Arunesh_Singh
Your example is different that his. Replace Integer with List in @Ye_Shao’s swap example, it will behave the same.
Integer class doesn’t have methods like add, remove, replace, set that List has. For example you can’t do this.
Integer i = new Integer(10);
i.set(20); //there is no set method because you are not allowed to change the value within the object once it is created.

That’s why it’s called immutable. Again you are mixing it up, pass by reference behaviour has nothing to do with immutability.

One can create a custom list class that is immutable. Which means once list is created with items, you can’t add or remove items from it. Google’s Guava library has such list.
https://guava.dev/releases/23.0/api/docs/com/google/common/collect/ImmutableList.html

doc of add(int index, E element) method for immutable list says
Deprecated.
Unsupported operation.