Possible Duplicate:
Is it possible to write swap method in Java?
Given two values x and y, I want to pass them into another function, swap their value and view the result. Is this possible in Java?
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.
Not with primitive types (
int,long,char, etc). Java passes stuff by value, which means the variable your function gets passed is a copy of the original, and any changes you make to the copy won’t affect the original.Now, objects are a bit different, in that the “value” of an object variable is actually a reference to an object — and copying the reference makes it point at the exact same object.
Limitation being, you still can’t modify the values of
aorbthemselves (that is, you can’t point them at different objects) in any way that the caller can see. But you can swap the contents of the objects they refer to.BTW, the above is rather hideous from an OOP perspective. It’s just an example. Don’t do it.