Junior — Middle
What are the consequences of changing the reference to an object inside a method during program execution?
sobes.tech AI
Answer from AI
If you change the reference to an object inside a method (i.e., assign a new reference to the method parameter), it will not affect the object itself outside the method, because in Java, parameters are passed by value.
However, if you change the state of the object through its methods or fields (for example, modify the object's fields), these changes will be visible outside the method, since the object is passed by reference (more precisely, a copy of the reference is passed by value).
Example:
void modifyObject(MyObject obj) {
obj = new MyObject(); // local reference change, does not affect outside
obj.setValue(10); // change the state of the new object
}
void modifyState(MyObject obj) {
obj.setValue(20); // change the object's state, visible outside the method
}
Thus, changing the reference inside the method does not affect the object outside, but changing the object's state does.