English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Passing and Returning Objects in Java

We know that this is a core concept, in Java it is always passed by value rather than by reference, so in this article, we will focus on how to verify this concept when passing primitives to methods and passing references.

If an original type is passed as a parameter to a method, the value assigned to that original type will be passed to the method, and that value becomes the local value of the method, which means any changes made to this value by the method will not change the value of the primitive you passed to the method.

Now, in the case of passing a reference to a method again, Java follows the same pass-by-value rule, let's understand how it works.

We know that in Java, if a reference is assigned to the reference, the reference will retain the memory location of the object created, otherwise it will be initialized to null. One thing to remember is that the value of the reference is the memory location of the object allocated, so whenever we pass a reference to any method as a parameter, we are actually passing the memory location of the object allocated to that specific reference. Technically, this means that the target method has the memory location of the object we created and can access it. Therefore, if the target method accesses our object and makes changes to any of its properties more than the original object's value after the change.

Example

public class PassByValue {
   static int k =10;
   static void passPrimitive(int j) {
      System.out.println("the value of passed primitive is ") + j);
      j = j + 1;
   }
   static void passReference(EmployeeTest emp) {
      EmployeeTest reference = emp;
      System.out.println("The value of name property of our object is "+ emp.getName());
      reference.setName("Bond");
   }
   public static void main(String[] args) {
      EmployeeTest ref = new EmployeeTest();
      ref.setName("James");
      passPrimitive(k);
      System.out.println("Value of primitive after get passed to method is "+ k);
      passReference(ref);
      System.out.println("Value of property of object after reference get passed to method is "+          ref.getName());
   }
}
class EmployeeTest {
   String name;
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}

Output Result

The value of passed primitive is 10
Value of primitive after get passed to method is 10
The value of name property of our object is James
Value of property of object after reference get passed to method is Bond