Junior
How are parameters passed to methods in Java?
sobes.tech AI
Answer from AI
In Java, method parameters are passed by value.
Primitive types:
- A copy of the primitive value is passed. Changing the parameter inside the method does not affect the original variable outside.
// Example for primitive type
public void changeValue(int x) {
x = x + 10; // Modifies the copy of x inside the method
}
// Usage:
int original = 5;
changeValue(original);
// original remains 5
Objects (reference types):
- A copy of the reference to the object is passed. Both references (original and in the method parameter) point to the same object in memory.
- Modifying the object's state (e.g., calling a setter, changing fields) through the passed reference inside the method will affect the original object.
- Reassigning the parameter to a new object inside the method does not change the original reference outside.
// Example for reference type (object)
public class MyObject {
private int value;
public MyObject(int value) {
this.value = value;
}
public void setValue(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
public void modifyObject(MyObject obj) {
obj.setValue(100); // Changes the state of the original object
}
public void reassignObject(MyObject obj) {
obj = new MyObject(200); // The parameter obj now points to a new object, but the original reference remains unchanged
}
// Usage:
MyObject originalObject = new MyObject(10);
modifyObject(originalObject);
// originalObject now has value = 100
MyObject anotherObject = new MyObject(50);
reassignObject(anotherObject);
// anotherObject still points to the original object with value = 50
In short: The reference value (its address) is passed, not the object itself. This allows modification of the object through this reference, but does not allow changing the original reference to point to a different object.