New Tutorials:   TKINTER    KOTLIN    JAVASCRIPT    SASS/SCSS    PL/SQL
See the Tutorial List

Java is Strictly Pass by Value

In Java, it is very confusing whether java is pass by value or pass by reference.

When the values of parameters are copied into another variable, it is known as pass by value and when a reference of a variable is passed to a method then it is known as pass by reference.

It is one of the feature of C language where address of a variable is passed during function call and that reflect changes to original variable.

In case of Java, we there is no concept of variable address, everything is based on object. So either we can pass primitive value or object value during the method call.

Note: Java is strictly pass by value. It means during method call, values are passed not addresses.

Example:

Below is an example in which value is passed by value and changed them inside the function but outside the function changes are not reflected to the original variable values.

	
class Add
{ 
	int x, y; 
	Add(int i, int j) 
	{ 
		x = i; 
		y = j;
	}  
} 
class Demo
{ 
	public static void main(String[] args) 
	{ 
		Add obj = new Add(5, 10); 
		// call by value
		change(obj.x, obj.y);
		System.out.println("x = "+obj.x); 
		System.out.println("y = "+obj.y);
		
	} 
	public static void change(int x, int y) 
	{  
		x++;
		y++;
	} 
}

	

x = 5 y = 10

Lets take another example in which an object is passed as value to the function, in which we change its variable value and the changes reflected to the original object. It seems like pass by reference but we differentiate it. Here member of an object is changed not the object.

Example:

Below is an example in which value is passed and changes are reflected.

	
class Add
{ 
	int x, y; 
	Add(int i, int j) 
	{ 
		x = i; 
		y = j;
	}  
} 
class Demo
{ 
	public static void main(String[] args) 
	{ 
		Add obj = new Add(5, 10); 
		// call by value (object is passed)
		change(obj);
		System.out.println("x = "+obj.x); 
		System.out.println("y = "+obj.y);
		
	} 
	public static void change(Add add) 
	{  
		add.x++;
		add.y++;
	} 
}
	

6 11