When learning Java, understanding how arguments are passed to methods is crucial, especially because it affects how data changes within your programs. Programmers often hear about call by value and call by reference—let’s clarify what these mean in the context of Java.
What Is Call by Value?
In call by value, a copy of the actual parameter’s value is made in memory. The method receives this copy, so any changes made inside the method do not affect the original variable.
Java: Always Call by Value
Java is strictly call by value. However, this can be confusing because objects seem to exhibit "by reference" behavior. What really happens is:
- When you pass a primitive type (like
int, double, boolean
), Java copies the actual value of the variable. - When you pass a reference type (like
objects
orarrays
), Java copies the reference (memory address), not the object itself. But the reference itself is passed by value.
Example: Call by Value with Primitive Types
java
public class Demo {
public static void main(String[] args) {
int a = 10;
changeValue(a);
System.out.println(a); // Output: 10
}
static void changeValue(int num) {
num = 20;
}
}
Explanation: The value of a does not change outside the method—modifications to num do not affect a.
Example: Passing Object References
java
class Person {
String name;
}
public class Demo {
public static void main(String[] args) {
Person p = new Person();
p.name = "Alice";
updateName(p);
System.out.println(p.name); // Output: Bob
resetReference(p);
System.out.println(p.name); // Output: Bob
}
static void updateName(Person person) {
person.name = "Bob"; // This changes the original object's field
}
static void resetReference(Person person) {
person = new Person(); // This does NOT change the original reference
person.name = "Charlie";
}
}
Explanation:
- In
updateName
, the object's content is modified so the change is visible outside the method. - In
resetReference
, only the copy of the reference (inside the method) is changed—this does not affect the caller’s variable.
Why Does This Matter?
- Modifying fields inside the object is visible to the caller.
- Assigning a new object to the parameter inside the method is not reflected outside.
Key Takeaways
- Java is always call by value—but for objects, what’s passed is a copy of the reference.
- You can modify the object that the reference points to, but you cannot change which object the caller variable points to.
Visual Recap
Parameter Type | What’s Passed | Modifying in Method Affects Caller? |
---|---|---|
Primitive | (int) Value (copy) | No |
Object Reference | Reference (copy) | Object content: Yes, Reference itself: No |
Understanding this behavior helps you avoid subtle bugs and write more robust Java code!
Check out the YouTube Playlist for great java developer content for basic to advanced topics.
Please Do Subscribe Our YouTube Channel for clearing programming concept and much more ... : CodenCloud
Top comments (1)
👏🏻