Java follows Pass by Value and not Pass by Reference for parameter passing mechanism.

While talking about pass by value and pass by reference, first we should understand what is pass by value and pass by reference and then we can jump into example of pass by value in Java. Just keep in mind, there is no pass by reference in Java.

What is Pass by Value?

When an parameter is passed to a method, the actual parameter is copied and the copied value is passed as argument. Any change on the copied argument affects only the copied argument and not on the actual variable/parameter. Java follows this mechanism and hence Java is Pass by Value.

What is Pass by Reference?

In pass by reference, when the parameter is passed, formal parameter is just an alias to the actual parameter. It refers to the actual argument. Any changes done to the formal argument will reflect in actual argument and vice versa.

Pass by value versus Pass by reference check in Java

Let’s see an example in Java to check whether it uses pass by value or pass by reference.

class AddresBook{
  String name;

  public AddressBook(String name) {
    this.name = name;
  }

  public String toString() {
    return name;
  }
}
public class SwapTest{

  public static void main(String args[]) {
    AddressBook a1 = new AddressBook("Ben");
    AddressBook a2 = new AddressBook("John");

    System.out.println("Before Swap- a1: " + a1 + " | a2: s" + a2);
    swap(a1, a2);
    System.out.println("After Swap- a1: " + a1 + " | a2: " + a2);
  }

  public static void swap(AddressBook contact1, AddressBook contact2) {
    AddressBook temp = new AddressBook("");
    temp = contact1;
    contact1 = contact2;
    contact2 = temp;
  }

}

Output

Before Swap- a1: Ben | a2: John
After Swap- a1: Ben | a2: John

In above example, we tried to swap two arguments but there is no change in actual variable value before and after swap which confirms Java follows Pass by Value. If there is change in value before and after swap then we could have confirmed Java is Pass by Reference but it failed.

Conclusion

“The reference is copied as a value” to a new variable and it is given as parameter to the called method. It does not directly pass a1 variable which is the actual argument. This is the key difference between pass by value and pass by reference.

Please follow and like us: