Passing and Returning Objects in Java

Java 8Object Oriented ProgrammingProgramming

As we know it is core concept that in Java there is always pass by value and not by pass by reference.So in this post we will focus on that how this concept get validated in case of passing primitive and passing reference to a method.

In case when a primitive type is passed to a method as argument then the value assigned to this primitive is get passed to the method and that value becomes local to that method,which means that any change to that value by the method would not change the value of primitive that you have passed to the method.

While in case of passing reference to a method again Java follow the same rule of pass by value now let understand how it happens.

As we know that a reference in Java holds the memory location of object created if it is assigned to that reference otherwise it is initiated as null.Now the point to remember here is that the value of the reference is the memory location of the assigned object,so whenever we pass the reference to any method as argument then we actually pass the memory location of that object which is assigned to that particular reference.This technically means that the target method has memory location of our created object and can access it to.So in case if target method access our object and make changes to any of property of it than we would encounter with the changed value in our original object.

Example

 Live Demo

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

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
raja
Published on 01-Nov-2018 06:06:27
Advertisements