OBJECT ORIENTED PROGRAMMING THROUGH JAVA : Unit - 2 : Topic - 9 : Passing Arguments by Value and by Reference in Java
Unit - 2
Topic - 9 : Passing Arguments by Value and by Reference in Java
When a method is called in a programming language, the way the arguments are passed determines how changes inside the method affect the original variables.
1. Call by Value
-
In call by value, a copy of the variable's value is passed to the method.
-
Changes made inside the method do not affect the original variable.
In Java:
-
All primitive data types (
int,float,char, etc.) are passed by value.
Example: Call by Value
Output:
💡 Explanation:
Inside meth(), the changes are applied to copies of a and b, not the originals.
2. Call by Reference
-
In call by reference, the actual reference (address) of the variable is passed to the method.
-
Changes made inside the method affect the original object.
✅ In Java:
-
Objects are passed by value of reference (also called “pass-by-value, where the value is a reference”).
-
This means a copy of the reference is passed, allowing modification of the object’s data.
Example: Call by Reference Behavior in Java
Output:
💡 Explanation:
Here, the reference to ob is copied, but both the original and the copy point to the same object.
Thus, modifying obj.x and obj.y changes the original ob.
Key Points
-
Java is always pass-by-value.
-
For primitives → value of the variable is copied → no change in original.
-
For objects → value of the reference is copied → changes affect the same object.
Comments
Post a Comment