Pass by Value

Pass by Value

 

Technically in java, we don’t have pass by reference. All the calls made to methods passing arguments are pass by value.

 

Let’s understand this for 2 scenarios :

  • passing primitive data Types.
  • passing reference of an Object.

 

Primitive data Type


package com.diaryreaders.corejava.passbyvalue;
/**
* @author Gaurav Gupta
*
*/
public class Pass {
private int a = 0;
private static void function(int a) {
a = 100;
}
private void function() {
function(a);
System.out.println(a);
}
public static void main(String[] args) {
Pass pObj = new Pass();
pObj.function();
}
}


 
Output:

 

In the above code, main method is calling function by reference of Pass Object i.e. pObj.function() which invoked the method named as function(). function() Method further invoked the method named as function(int a) which accept int a. so the passed value a = 0 from function() is being copied to function(int a) variable a. Any changes made to the local variable of function(int a) won’t reflect outside of the function.

 

Memory Visualization

 
Passing reference of an Object


/**
* 
*/
package com.diaryreaders.corejava.passbyreference;
/**
* @author Gaurav Gupta
*
*/
public class Pass {
private int a = 10;
private static void function(Pass pObj) {
pObj.a = 100;
}
public static void main(String[] args) {
Pass pObj = new Pass();
function(pObj);
System.out.println(pObj.a);
}
}


 
Output:

 

In the above code, main method is calling function by reference of Pass Object i.e. pObj.function(Pass pObj) which accept Object of type Pass class. So the passed reference pObj is being copied to function(Pass pObj) pObj reference variable. Any changes made to the local reference of function(Pass pObj) will reflect outside of the function as both references pointing to the same object in the memory.

 

Memory Visualization

1 Comment

Leave a Reply

Your email address will not be published.

Lorem ipsum dolor sit amet, consectetur a dipiscing elit. Vivamus leo ante,

FOLLOW US ON