aspose file tools*
The moose likes Beginning Java and the fly likes pass by reference Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "pass by reference" Watch "pass by reference" New topic
Author

pass by reference

James Knight
Greenhorn

Joined: Mar 18, 2002
Posts: 7
if objects are passed by reference and not by copy. Can someone explain why it doesnt print 4 3
class Swap {
public static void swap(Integer x, Integer y) {
Integer temp = x;
x = y;
y = temp;
}
public static void main (String [] args) {
Integer i = new Integer(3);
Integer j = new Integer(4);
swap(i,j);
System.out.println(i + " " + j);
}
}
Dave Vick
Ranch Hand

Joined: May 10, 2001
Posts: 3244
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
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,
James Knight
Greenhorn

Joined: Mar 18, 2002
Posts: 7
Dave
Thanks for the great answer. You explained it really well.
James
Valentin Crettaz
Gold Digger
Sheriff

Joined: Aug 26, 2001
Posts: 7610
You may also want to check out the following link:
http://www.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=24&t=015081


SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: pass by reference