In java everything is reference, so when you have something like:
Point pnt1 = new Point(0,0);
Java does following:
- Creates new Point object
- Creates new Point reference and initialize that reference to point (refer to) on previously created Point object.
- From here, through Point object life, you will access to that object through pnt1
reference. So we can say that in Java you manipulate object through its reference.
Java doesn't pass method arguments by reference; it passes them by value. I will use example from this site:
public static void tricky(Point arg1, Point arg2) {
arg1.x = 100;
arg1.y = 100;
Point temp = arg1;
arg1 = arg2;
arg2 = temp;
}
public static void main(String [] args) {
Point pnt1 = new Point(0,0);
Point pnt2 = new Point(0,0);
System.out.println("X1: " + pnt1.x + " Y1: " +pnt1.y);
System.out.println("X2: " + pnt2.x + " Y2: " +pnt2.y);
System.out.println(" ");
tricky(pnt1,pnt2);
System.out.println("X1: " + pnt1.x + " Y1:" + pnt1.y);
System.out.println("X2: " + pnt2.x + " Y2: " +pnt2.y);
}
Flow of the program:
Point pnt1 = new Point(0,0);
Point pnt2 = new Point(0,0);
Creating two different Point object with two different reference associated.
System.out.println("X1: " + pnt1.x + " Y1: " +pnt1.y);
System.out.println("X2: " + pnt2.x + " Y2: " +pnt2.y);
System.out.println(" ");
As expected output will be:
X1: 0 Y1: 0
X2: 0 Y2: 0
On this line 'pass-by-value' goes into the play...
tricky(pnt1,pnt2); public void tricky(Point arg1, Point arg2);
References pnt1
and pnt2
are passed by value to the tricky method, which means that now yours references pnt1
and pnt2
have their copies
named arg1
and arg2
.So pnt1
and arg1
points to the same object. (Same for the pnt2
and arg2
)
In the tricky
method:
arg1.x = 100;
arg1.y = 100;
Next in the tricky
method
Point temp = arg1;
arg1 = arg2;
arg2 = temp;
Here, you first create new temp
Point reference which will point on same place like arg1
reference. Then you move reference arg1
to point to the same place like arg2
reference.
Finally arg2
will point to the same place like temp
.
From here scope of tricky
method is gone and you don't have access any more to the references: arg1
, arg2
, temp
. But important note is that everything you do with these references when they are 'in life' will permanently affect object on which they are point to.
So after executing method tricky
, when you return to main
, you have this situation:
So now, completely execution of program will be:
X1: 0 Y1: 0
X2: 0 Y2: 0
X1: 100 Y1: 100
X2: 0 Y2: 0