Originally Posted by
helloworld922
The reasons why objects are passed by reference
Hey, I don't mean to be nit-picky, but I think this might be a bit misleading. In Java, everything, including Objects, is passed by value. More accurately, the Object's reference is passed by value (stick with me, it might sound like I'm splitting hairs but this matters).
We all know that primitives are passed by value, proved by this:
public class PassByValueTest(){
public static incrementVariable(int x){
x = x + 1;
}
public static void main(String... args){
int i = 2;
incrementVariable(i);
System.out.println(i); //outputs 2
}
}
And it might look like Objects are passed by reference, because we can change what's passed, like so (not tested, might contain syntax errors, but hopefully gets the point across):
public class PassByValueTest(){
public static class WrapperClass{
public int wrappedInt = 2;
}
public static incrementVariable(WrapperClass x){
x.wrappedInt = x.wrappedInt+1;
}
public static void main(String... args){
WrapperClass wc = new WrapperClass();
incrementVariable(wc);
System.out.println(wc.wrappedInt); //outputs 3
}
}
However, that does not mean that wc is being passed by reference. If it were, we could do this:
public class PassByValueTest(){
public static class WrapperClass{
public int wrappedInt;
public WrapperClass(int w){
wrappedInt = w;
}
}
public static incrementVariable(WrapperClass x){
x = new WrapperClass(x.wrappedInt+1);
}
public static void main(String... args){
WrapperClass wc = new WrapperClass(2);
incrementVariable(wc);
System.out.println(wc.wrappedInt); //outputs 2
}
}
I don't think I'm explaining it very well, so instead, maybe just read:
JavaRanch Campfire - Cup Size: a Story About Variables
and its follow-up:
JavaRanch Campfire - Pass By Value, Please
Sorry to be a nitpicker, but this is something that a lot of intermediate or even advanced Java programmers get confused. I just wanted to clear up any confusion before we perpetuate the misconception that Java passes primitives by value and Objects by reference.
In Java, everything is passed by value. Even references. That's not as confusing as it sounds.