Is Java Pass by Value or Pass by Reference?

Java is “pass Reference as a Value”, what does this mean?

Java is passing Object reference as a value & the primitive types are pass by value.

First of all, what is the difference between “pass by Value” & “pass by Reference”:

  • Pass by Value:
    • If I have a Google document & I send you the content of the page, I’m passing by value.
    • The content passed now is a disconnected copy of the original.
    • Any changes in the original document won’t be reflected on your copy, also any changes you will apply to the content sent to you won’t be reflected on the original one.
    • That’s what is meant by “Pass by Value”.
  • Pass by Reference:
    • If I share the document URL with you, I’m passing by reference.
    • Any changes in the original document will be reflected on your copy, also any changes you will apply to the page will be reflected on the original one. Because both are the same reference.

Why is Java “pass Reference as a Value”  ?

Let’s check this code snippet

public static void main(String[] args) {
    List list1 = new ArrayList<>();
    list1.add(1);
    list1.add(2);

    mapTheReferenceToNewAddress(list1);
    System.out.println(list1);
}

public static void mapTheReferenceToNewAddress(List<Integer> list2){
    list2 = new ArrayList<>(); 
    list2.add(3); 
}

The output for this code would be [1, 2] not [3].

Because the reference of list1 is passed as a value which is list2, so when this line is executed

list2 = new ArrayList<>();

list2 reference now is changed to point to a new address in the memory, not the old one. So the changes in list2 are not reflected on the original one (list1).


Let’s check another code snippet

public static void main(String[] args) {
    List list1 = new ArrayList<>();
    list1.add(1);
    list1.add(2);

    addNewIntegerToTheList(list1);

    System.out.println(list1);
}

public static void addNewIntegerToTheList(List<Integer> list2){
    list2.add(3);
}

The output for this code would be [1, 2, 3]. Because list1 & list2 points to the same memory address, so changes are reflected.