How to get a result of a function from another function?

It’s not entirely clear what you want to do here, but it seems like you have two options…

You can store the value in a class-level variable:

private int sum = 0;
public void Calculate (int a, int b) {
    sum = a + b;
}
public int getResult() {
    return sum;
}

Or, probably more effectively, just return the value from the function which calculates it:

public int Calculate (int a, int b) {
    return a + b;
}

Unless there’s a particularly good reason otherwise, it’s usually better to just do the simplest thing possible. Which in this case is just to add the numbers and return the result. Otherwise consuming code will need to remember to always call Calculate() before calling getResult() and will create a dependency on the order of operations when using the object.

Leave a Comment