Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

pass by reference

 
James Knight
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3244
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 Vick
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dave
Thanks for the great answer. You explained it really well.
James
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic