articles

home / developersection / articles / pass by value vs. pass by reference in java

Pass by Value vs. Pass by Reference in Java

Pass by Value vs. Pass by Reference in Java

Ashutosh Kumar Verma 442 20-Mar-2025

In Java, all arguments to methods arepass by value, which means that a copy of the actual value is passed to the method. However, how this behaves depends on whether the argument is a primitive type or a reference type.

 

Pass by Value (Primitive Data Types)

When a primitive type (e.g., int, double, char, etc.) is passed to a method, and Java passes a copy of the actual value. Any modifications inside the method do not affect the original variable.

 

Example

class Test {
   static void modifyValue(int x) {
       x = 50; // Changes only the copy, not the original
       System.out.println("Value in method: " +x); // Output: 50
   }
   public static void main(String[] args) {
       int num = 10;
       modifyValue(num);
       System.out.println("After method call: " + num); // Output: 10
   }
}

Explanation

  • The method modifyValue(int x) receives a copy of num.
  • Any changes to x inside the method do not affect num in main().

 

Pass by Reference (Reference Types)

When an object reference is passed, Java still passes it by Reference, which means that a copy of the reference (memory address) is passed. However, since both the original and copied references point to the same object, modifications inside the method affect the original object.

 

Example

class Test {
    static void modifyObject(Person p) {
        p.name = "Balaji"; // Modifies the actual object
    }

    public static void main(String[] args) {
        Person person = new Person();
        person.name = "Jagdamb";

        modifyObject(person);
        System.out.println("After method call: " + person.name); // Output: John
    }
}

 class Person {
    String name;
}

Explanation

  • The modifyObject(Person p) method gets a copy of the reference.
  • person (in main) and p (in modifyObject) both point to the same object.
  • Changing p.name also affects person.name.

 

Key Points

  • Java always passes arguments by value.
  • Primitive values ​​are copied, so changes do not affect the original variable.
  • Object references are copied, but both copies point to the same object, so changes affect the original object.
  • Java does not support true "pass by reference" like C++.

 

Thanks!

 

Also, Read: Abstraction and Interfaces in Java

 


Updated 20-Mar-2025

Hi! This is Ashutosh Kumar Verma. I am a software developer at MindStick Software Pvt Ltd since 2021. I have added some new and interesting features to the MindStick website like a story section, audio section, and merge profile feature on MindStick subdomains, etc. I love coding and I have good knowledge of SQL Database.

Leave Comment

Comments

Liked By