|
|
Operators and Assignments - Method Invocation
- when you pass a primitive value to a method, a copy of the value is made available to the method, not the value itself
- any changes made to the value in the method do not affect the original value
int i = 50;
changeValue(i); // where method multiplies i by 3
Output:
Original value of i: -> 50
Value of i in the method: -> 150
Value of i after method invocation: -> 50
Passing object references
- when you pass an object reference to a method, a copy of the reference is passed. Operations in the method which change the object reference do not affect the original; however, changes to the object itself within the method affect the original object
int[] array = { 10,10,10 } // original array
changeObjectReference(array) // set the reference to a new array
changeActualObject(array) // set the 2nd element of the array
Output:
Original array values: 10, 10, 10
Array in the method: 20, 20, 20
After Object reference changed in method: 10, 10, 10
After object changed in method: 10, 20, 10
Method invocation conversion (JLS §5.3)
- each argument is converted to the type of the method parameters
- widening conversion is implicit
- narrowing conversion is not implicit (values must be cast)
Also see:
Example Code
Traps
- code that results in a primitive value being changed in a method (can't happen)
- code that results in an unchanged object value when it was changed in a method
- failing to cast a value to match a method parameter type ie assuming narrowing conversion on a method call
|