Creating reference to a primitive - Roberts-Heller's cert guide?
divyasheel sharma
Greenhorn
Joined: Feb 15, 2001
Posts: 19
posted
0
How to create reference to a primitive : This is from Page 21 RH Guide for JCP Exam, I couldn't make out what this means: Can someone explain the code for me please : public class PrimitiveReference { public static void main(String args[]) { int[] myValue = {1}; modifyIt(myValue); System.out.println("myValue contains"+myValue[0]); } public static void modifyIt(int [] value) { value[0]++; } } Thanks Divya
Eat Java,Drink Java...surf only Javaranch!
Scott Pedigo
Greenhorn
Joined: Feb 15, 2001
Posts: 15
posted
0
I think the point that the example is trying to illustrate is that a copy of the *reference* to the integer array is passed into the method on the stack, not a separate copy of the array itself. So when in the method the value of the array element is changed, the original is changed. If a copy of the array contents were passed in on the stack, then only the copy on the stack would be changed, and the original would remain unchanged (which is not the case). The output should therefore show the change.
divyasheel sharma
Greenhorn
Joined: Feb 15, 2001
Posts: 19
posted
0
Hi Steve! But how do I know that its the copy or the separate copy that is passed to the method? Please explain bit more. thanx Divya
divyasheel sharma
Greenhorn
Joined: Feb 15, 2001
Posts: 19
posted
0
Hi Steve! But how do I know that its the copy or the separate copy that is passed to the method? Please explain bit more. thanx Divya
Pat Barrett
Ranch Hand
Joined: Jan 03, 2001
Posts: 63
posted
0
When an array is passed into a method it is a reference, not a copy of a reference. HTH Pat B.
Cindy Glass
"The Hood"
Sheriff
Joined: Sep 29, 2000
Posts: 8521
posted
0
Primitives always pass a copy of the primitive. Objects always pass a copy of the reference to the object. myValue holds a reference to the array (that is an object). modifyIt(myValue) is taking in a copy of that reference.