Possible Duplicate:
Java, pass-by-value, reference variables
Consider the following simple java program
class main{
public static void main(String args[]){
int x = 5;
change(x);
System.out.println(x);
}
static void change(int x){
x = 4;
}
}
Since java uses pass by value the value of x will not change in the main..To overcome this problem we have the concept of pass by reference in c..But i do not find any such concept in java..How can i really change the value of x..? If there is no way of changing x then is this not a disadvantage of java?
You can't change the value of
xin the calling code withinchange. (It would have been clearer if you'd used two different variable names.) I don't find it makes my life harder in Java - you can use pass by reference in C#, but it's rarely a good idea.Pass by value is usually easier to understand, and leads to simpler code. Usually I either want a method to simply compute something - in which case that should be the return value - or I want to mutate an object; preferably the object I call the method on, but potentially an object which I indicate by passing a reference by value for one of the parameters. I very, very rarely wish I could change the value of a variable in the calling code other than by using simple assignment.
(Oh, and C doesn't have pass-by-reference either, by the way. It allows you to pass pointers by value, but that's not the same thing.)