0

I'm learning Java and I cant figure this out. I have a simple change function that changes the value of 2 parameters between them. If x = 5 and y = 7, after execution x= 7 and y =5. Is there a way in Java to keep those values changed like in c++ where you use &x, &y?

public static void change(int x, int y){
    x=x+y;
    y=x-y;
    x=x-y;
}    
Gaurav Jeswani
  • 4,410
  • 6
  • 26
  • 47
yeahman14
  • 75
  • 1
  • 6
  • You can't, you have to *return* the changed values or pass in reference types with mutable contents, not primitives. – luk2302 Sep 13 '19 at 11:59

1 Answers1

0

In Java int is a primitive type. So for any primitive type you can't do it. There is a boxed primitive for every primitive in Java, but here Integer is immutable (once initialized can't change it's state) so even using Integer won't work.

So you have two solutions:

1) Use MutableInt from apache commons jar.

2) Create a wrapper class for it as below and use that.

public class MutableInt {

private int myInt; //default initialized with 0

public int getMyInt(){
 return myInt;
}

public void setMyInt(int myInt) {
 this.myInt = myInt;
}

}

And inside the change method

public static void change(MutableInt x, MutableInt y){
    x.setMyInt(x.getMyInt() + y.getMyInt());
    y.setMyInt(x.getMyInt() - y.getMyInt());
    x.setMyInt(x.getMyInt() - y.getMyInt());
} 

Then when you get the value from x or y using x.getMyInt() or y.getMyInt(), you will get updated value.

Gaurav Jeswani
  • 4,410
  • 6
  • 26
  • 47