james642 Welcome to the Java Ranch, we hope you’ll enjoy visiting as a regular however, your name is not in keeping with our naming policy here at the ranch. Please change your display name to an appropriate name as shown in the policy. Thanks again and we hope to see you around the ranch!!

Dave

Dave Vick
Ranch Hand

Joined: May 10, 2001
Posts: 3244

posted Mar 18, 2002 19:24:00

0

James To be exact objects are passed by value but the value of an object is actually its reference in memory. What is happening in the code you posted is this: Integer i = new Integer(3); Integer j = new Integer(4); swap(i,j); These three lines create the Integer objects and pass their references to the swap method. swap(Integer x, Integer y) { Integer temp = x; x = y; y = temp; In the swap method the local variables x and y receive the references to the Integer objects you passed and and then swaps them. Now x refers to the Integer that y refered to and y referes to the one x refered to. System.out.println(i + " " + j); Now, back in the main method, it prints out the values of the objects refered to by i and j. But i and j still refer to the same objects they always did, it was only the local variables in the method that got swapped not i and j. All the method did was to change the references that the variables pointed to. It did not change the underlying objects. Try to modify your code to have swap change the values of the objects then you'll see that the printed objects did indeed change. hope that helped,