In Java, all arguments to methods arepass by value
, which means that a copy of the actual value is passed to the method. However, how this behaves depends on whether the argument is a
primitive type or a reference type.
Pass by Value (Primitive Data Types)
When a primitive type (e.g., int
, double
,
char
, etc.) is passed to a method, and Java passes a copy of the actual value. Any modifications inside the method do not affect the original variable.
Example
class Test {
static void modifyValue(int x) {
x = 50; // Changes only the copy, not the original
System.out.println("Value in method: " +x); // Output: 50
}
public static void main(String[] args) {
int num = 10;
modifyValue(num);
System.out.println("After method call: " + num); // Output: 10
}
}
Explanation
- The method
modifyValue(int x)
receives a copy ofnum
. - Any changes to
x
inside the method do not affectnum
inmain()
.
Pass by Reference (Reference Types)
When an object reference is passed, Java still passes it by Reference, which means that a copy of the reference (memory address) is passed. However, since both the original and copied references point to the same object, modifications inside the method affect the original object.
Example
class Test {
static void modifyObject(Person p) {
p.name = "Balaji"; // Modifies the actual object
}
public static void main(String[] args) {
Person person = new Person();
person.name = "Jagdamb";
modifyObject(person);
System.out.println("After method call: " + person.name); // Output: John
}
}
class Person {
String name;
}
Explanation
- The
modifyObject(Person p)
method gets a copy of the reference. person
(inmain
) andp
(inmodifyObject
) both point to the same object.- Changing
p.name
also affectsperson.name
.
Key Points
- Java always passes arguments by value.
- Primitive values are copied, so changes do not affect the original variable.
- Object references are copied, but both copies point to the same object, so changes affect the original object.
- Java does not support true "pass by reference" like C++.
Thanks!
Also, Read: Abstraction and Interfaces in Java
Leave Comment