See the Tutorial List

Java is Strictly Pass by Value

In Java, it is very confusing whether java is Pass by Value OrPass by Reference. When the values of Parameter are copied into another variable. The copied objects are passed, it is known as Pass by Value. And when a reference of a parameter is passed to a method then it is known as Pass by Reference.

Java is strictly Pass by Value.


Below is an example in which value is passed by reference but changes are not reflected back to main()

Example:

	
class Add
{ 
int x, y; 
Add(inti, int j) 
	{ 
		x = i; 
		y = j;
	} 
Add()      
	{ 
		x = 0; 
		y = 0;
	} 
} 
class PassRefDemo1
{ 
    public static void main(String[] args) 
    { 
        Add obj = new Add(5, 10); 
        change(obj);
	int z = obj.x + obj.y;
System.out.println("Total = "+z); 
    } 
    public static void change(Add obj) 
    {  
obj = new Add(); 
obj.x = 10; 
	obj.y = 10;
    } 
}
	

java-pass-by-value

Below is an example in which value is passed and changes are reflected back to main()

Example:

	
class Add
{ 
int x, y; 
Add(inti, int j) 
	{ 
		x = i; 
		y = j;
	} 
Add()      
	{ 
		x = 0; 
		y = 0;
	} 
} 

class PassDemo1
{ 
    public static void main(String[] args) 
    { 
        Add obj = new Add(5, 10); 
        change(obj);
	int z = obj.x + obj.y;
System.out.println("Total = "+z); 
    } 
    public static void change(Add obj) 
    {  
obj.x = 10; 
	obj.y = 10;
    } 
}
	

java-pass-by-value