Does Java pass by value or pass by reference?

 

Java does only pass by value and doesn't pass method arguments by reference, instead it passes Object reference by its value as method parameter. Java copies and passes the reference by value, not the object, hence if we modify Object values in method then original objects will get modified, since both references point to the original objects. 
Below are the 2 diagrams which we can see how primitive types work when we pass to another methods and how Objects work when we pass to another methods. Basically primitive types will create new variable in stack and it manipulates on it, but when we pass Objects it creates new reference and its passes the value of reference. Again Java does only pass by value and doesn't use pass by reference. 

When we pass primitive datatype to another method.
Does Java pass by value or pass by reference?
When we pass Object to another method.


Now lets see simple example in java as how it works. Lets create Employee class for Object passing.


public class Employee{
 
 private String name;

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 } 
}

Next we will create main class which will initiate Employee Object and pass to another method along with integer primitive datatype.


public class MyTest {
 
 public static void main(String[] args) {
  
  Employee obj = new Employee();
  obj.setName("JAVA");// IMP
  
  int _int = 100;
  
  MyTest ob1 = new MyTest();
  ob1.changeValue(obj, _int);
  
  System.out.println("Inside Main Method : "+obj.getName()+ " : "+_int);
 }
 
 public void changeValue(Employee mObj, int mInt){
  
  mObj.setName("DISCOVER");
  
  mInt = 99;
  
  System.out.println("Inside another Method : "+mObj.getName() + " : "+mInt);
 }
 
}

OUTPUT:


Inside another Method : DISCOVER : 99
Inside Main Method : DISCOVER : 100

No comments:
Write comments