Java, Java, Java: Object-Oriented Problem Solving by R. Morelli & R. Walde
9.5.4 Passing a Value and Passing a Reference
Recall from Chapter 3 that when an Object is passed to a method, a copy of the reference to theObject is passed. Because an array is an object, a reference to the array is passed toinsertionSort(), rather than the whole array itself. This is in contrast to how a value of a primitive type is passed. In that case, a copy of the actual value is passed.
Passing a primitive value
Passing an object JAVA LANGUAGE RULE Primitive vs. Object Parameters. When a value of a primitive data type—int, double, char, boolean— is passed as an argument to a method, a copy of the value is passed; when a reference to anObject is passed, a copy of the reference is passed.
One implication of this distinction is that for arguments of primitive type, the original argument cannot be changed from within the method because the method has only a copy of its value. For example, the following method takes anint parameter n, which is incremented within the method:
¨ p u b l i c void add1 ( i n t n ) {
System . out . p r i n t ( ”n = ” + n ) ;
n = n + 1 ;
System . out . p r i n t l n ( ” , n = ” + n ) ;
}
© But because n is a parameter of primitive type, incrementing it within the method has no effect on its associated argument. Thus, in the following segment, the value of Num—n’s associated argument—will not be affected by what goes on inside theadd() method. The output produced by the code segment is shown in the comments:
¨ i n t Num = 5 ;
System . out . p r i n t l n ( ”Num = ” + Num) ; / / P r i n t s Num = 5 add1 (Num ) ; / / P r i n t s n = 5 , n = 6 System . out . p r i n t l n ( ”Num = ” + Num) ; / / P r i n t s Num = 5
© Note that while n’s value has changed inside the method, Num’s value remains unaffected.
The case is much different when we pass a reference to an object. In that case, the object itself can be manipulated from within the method. TheinsertionSort() method is a good illustration. In the following code segment, the arrayanArr is printed, then sorted, and then printed again:
¨ S o r t s o r t e r = new S o r t e r ( ) ;
i n t anArr [ ] = { 5 , 1 0 , 1 6 , −2 , 4 , 6 , 1 };
s o r t e r . p r i n t ( anArr ) ; / / P r i n t s 5 1 0 1 6 −2 4 6 1 s o r t e r .