Methods define what objects can do. Void methods perform actions without returning a value. Non-void methods evaluate a return expression and hand back a single value. Primitives are passed by value, so the original argument never changes. Object references are also passed by value, but because the parameter holds a copy of the reference, the method can still modify the original object's state through that shared reference.
- Return by value: A non-void method evaluates its return expression and sends the result back to the caller. Code after a return statement in the same block never executes.
- Accessor method: A public non-void method that returns a copy of an instance variable's value, allowing outside classes to read state without direct access to the private field.
- Mutator method: A public void method that updates an instance variable, giving outside classes a controlled way to change object state.
- Object reference parameter: When an object is passed to a method, the parameter receives a copy of the reference. The method can call methods on the object and change its state, but reassigning the parameter does not affect the original variable.
- Side effect: An action a method performs beyond returning a value, such as printing output or modifying an instance variable. Mutator methods intentionally produce side effects.
If a method receives an int parameter and doubles it, does the original int variable in the caller change? What if the parameter is an ArrayList?
| Parameter type | What is copied | Can method change original? |
|---|
| Primitive (int, double, boolean) | The value itself | No |
| Object reference | The reference (memory address) | Yes, through the shared reference |