Tuesday, July 7, 2009

Java uses Pass-by-Value and no pass-by reference

Java uses Pass-by-Value and no pass-by reference

Java does manipulate objects by reference, and all object variables are references.
However, Java doesn't pass method arguments by reference; it passes them by value.
 public void swap1(int var, int var2) { 
int temp = var1;
var1 = var2;
var2 = temp;
}

When swap1() returns, the variables passed as arguments will still hold their original values.
The method will also fail if we change the arguments type from int to Object, since Java passes object references by value as well.
 public void swap2(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.printIn("X= " + pnt1.x + " Y=" + pnt1.y);
System.Out.printIn("X= " + pnt2.x + " Y=" + pnt2.y);
}

IF we execute this main() method, we see the following output:
X= 0 Y= 0
X= 0 Y= 0
X= 100 Y= 100
x= 0 y= 0

No comments: