1

I am working on simple example.Initially taking the value of a as 1 and b as 2. I am calling method to do an update, when I print this a and b. It will be 1 and 2 as expected. But I should update this a and b in each loop, How can I do this?I am getting thought of returning as list. Is there a simple way to accomplish it?

public class UpdateTest {

    public static void main(String[] args) {
        int a=1;
        int b=2;
        for (int i = 0; i < 5; i++) {
            update(a,b);
        }

       System.out.println(a+"------"+b);
    }

    private static void update(int a, int b) {
        // TODO Auto-generated method stub
        for (int i = 0; i < 10; i++) {
            a++;
            b++;
        }
    }

}
2
  • 2
    Java is always pass-by-value. Commented Nov 9, 2015 at 15:54
  • @ElliottFrisch I think he knows that and is just wonder how to easily return 2 values (the values of a and b) Commented Nov 9, 2015 at 15:54

2 Answers 2

2

You can put the values in a class e.g.

class Pair {
    int a, b;
    Pair(int a, int b) {
        this.a = a;
        this.b = b;
    }
}

Initialize it like this

Pair pair = new Pair(1, 2);

Then modify the update method accordingly

private static void update(Pair pair) {
    for (int i = 0; i < 10; i++) {
        pair.a++;
        pair.b++;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Its not very nice but will do the job: You can simply return an array containing the values of a and b.

public class UpdateTest {

    public static void main(String[] args) {
        int a=1;
        int b=2;
        for (int i = 0; i < 5; i++) {
            int[] ret = update(a,b);
            a = ret[0];
            b = ret[1];
        }

        System.out.println("a= " + a + ", b= " +b);
    }

    private static int[] update(int a, int b) {
        for (int i = 0; i < 10; i++) {
            a++;
            b++;
        }
        int[] ret = {a,b};
        return ret;
    }
}

2 Comments

Why the loop instead of a += 10 and b+= 10 ?
I just took that part from the sourcecode the OP provided! Of course you're right, faster would be a+=10; b+=10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.