0

here is my code

public class Scale {

    public static void main(String[] args) {

        int x = 4;
        int y = 3;
        int faktor = 2;

        skaliere(x,y,faktor);

        System.out.println(x + " " + y);
    }

    public static void skaliere(int x, int y, int faktor){

        // ?

    }
}

I want to change the scale the x and y by faktor, not using a return value. Just by the skaliere method.

Tunaki
  • 132,869
  • 46
  • 340
  • 423

3 Answers3

4

I want to change the scale the x and y by faktor, not using a return value. Just by the skaliere method.

Note that Java is not pass by reference, it's always pass by value.

Without any hack, simply you can't because they are primitives. If they are mutable objects, yes you can change their state.

That hack would be making them static and assigning values inside that method.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
-1

You could do this with an object that wraps the two values. This is because the object reference is passed to the method. If you pass a primitive which are immutable, they will never be changed on the return, it would only change a copy in the method. Using an object, you can pass the containing values and it would be the ones referenced by the main method when retrieved.

public static void main(String[] args) {

    // org.eclipse.swt.graphics.Point
    Point p = new Point(0, 0);
    p.x = 4;
    p.y = 3;
    int faktor = 2;
    skaliere(p,faktor);

    System.out.println(p.x + " " + p.y);
}

public static void skaliere(Point p, int factor){
    p.x *= factor;
    p.y *= factor;
}
ergonaut
  • 6,929
  • 1
  • 17
  • 47
-1

You can always make your own MutableInteger class

class MutableInteger{
        private int value;

        public MutableInteger(int v){
            this.value = v;
        }

        public int get(){
            return value;
        }

        public void set(int newValue){
            this.value = newValue;
        }

        @Override
        public String toString() {
            return Integer.toString(value);
        }


    }

Then use it in your code:

public static void main(String[] args) {

    MutableInteger x = new MutableInteger(4);
    MutableInteger y = new MutableInteger(3);
        int faktor = 2;

        skaliere(x,y,faktor);

        System.out.println(x + " " + y);
    }

    public static void skaliere(MutableInteger x, MutableInteger y, int faktor){

        x.set(x.get() *faktor);
        y.set(x.get() *faktor);
    }

Since you are making your own class, you can even move the skaliere method into your MutableInteger

 class MutableInteger{
    ...
        public void skaliere(int faktor){
            this.value *=faktor;
        }
  }

which makes your code look like this:

 public static void skaliere(MutableInteger x, MutableInteger y, int faktor){

      x.skaliere(faktor);
      y.skaliere(faktor);
    }

You don't even need the static method anymore

dkatzel
  • 31,188
  • 3
  • 63
  • 67