Junior — Middle
How is parameter passing in Java methods implemented and how does it differ?
sobes.tech AI
Answer from AI
In Java, parameters are passed to methods by value (pass-by-value). This means that when a method is called, the value of the argument is copied.
- For primitive types (int, boolean, etc.), the actual value is copied.
- For objects, the value of the reference to the object is copied, meaning the pointer is copied, not the object itself.
Because of this, inside the method, you can change the state of the object that the parameter references, but you cannot change the reference itself to point to a different object.
Example:
void modify(int a, MyObject obj) {
a = 10; // changing the local copy
obj.value = 10; // changing the object's state
obj = new MyObject(); // changing the local copy of the reference, does not affect the external object
}
Calling this method will not change the value of the variable a outside the method, but it will change the value field of the object passed to obj.