2

I have class, and inside it code:

MyClass x= value1;
MyClass y= value2;

void change (MyClass x,y) {
 MyClass temporary= x;
 x=y;
 y=temp;
}

My question is why my objects would not change their values (x and y will point to values before running this method)? And how to make to change them?

Popacha
  • 45
  • 4
  • Java is call by value, rather than call by reference, see this post: http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value – Paul Lo Mar 02 '15 at 03:34

1 Answers1

3

Objects do not change their values because, well, your code does not change the object's values. It swaps references, which have been copied into parameters x and y, which are local to your change method.

If you would like to make the objects swap their values, give them a method to get and set whatever value(s) that they may be representing. The code would look like this:

void change (MyClass x,y) {
    MyClass temporary= new MyClass();
    temporary.copyFrom(x);
    x.copyFrom(y);
    y.copyTo(temporary);
}

copyTo is your added method that performs the copying of the internal state of MyClass. Here is a small example:

class MyClass {
    private String firstName;
    private String lastName;
    public MyClass(String first, String last) {
        firstName = first;
        lastName = last;
    }
    public void CopyFrom(MyClass other) {
        firstName = other.firstName;
        lastName = other.lastName;
    }
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523