Please advice why primitives being used as method’s parameters do a copy of its value while objects are used as is?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In Java, all arguments are passed by value – but in the case of reference types (i.e. everything other than a primitive) the value of a variable isn’t the object itself – it’s a reference to the object. Thus that reference is copied into the method’s parameter, so it refers to the same object.
Note that this doesn’t just apply to method calls:
Here,
xandyrefer to the same object, even though they’re separate variables. Thus when the contents of that object is changed via theappendcall through theyvariable, the change is visible via thexvariable too.I think of it as being a bit like giving someone the address of your house: if I give two people my home address, and one of them paints the door red, then when the second person visits the house, they’ll see the red door too. I’m not giving them my house itself, I’m giving them a way of getting to my house.
There are many, many articles about this – although unfortunately some will claim that objects are passed by reference in Java. They’re not – the references are passed by value, as I said above. Scott Stanchfield has a good article about this, amongst many others.