References vs Values in Method Calls

Part of: Using Objects

Java Passes Copies When you call a method, Java passes a copy of each argument's value. The key question is: a copy of what ? - For a primitive , the copy is the actual value. - For an object , the copy is the reference (the arrow), both the original and the copy point to the same object . Primitives Are Independent Changing a primitive parameter inside a method does not affect the caller's variable, because the method has its own copy: Object References Share State With objects, the copied reference still points to the original object, so changes to that object's state are visible to the caller. (Strings are immutable, so they cannot be changed this way, but a mutable object like an array can.) Reassignment Does Not Escape Reassigning the parameter to a new object does not affect the caller, because you only changed the local copy of the reference: Inside replace, the local arrow now points to a brand-new array, but the caller's arrow is untouched. The Mental Model - Mutating the object an argument points to - visible to the caller. - Reassigning the parameter itself - invisible to the caller. - Primitives - never affect the caller. Aliasing When two reference variables point to t

Challenge: Double Each Element