Newby Coder header banner

Call By Value

What is Call by Value

Call by value is a method of evaluating arguments in a function (or method) call

Function parameters(or formal parameters) are the names listed in the function definition

Function arguments(or actual parameters) are the real values passed to (and received by) the function when executed

In call by value, the argument expression (which can be a single value like a number, or an operation like addition of 2 numbers) is evaluated, and the resulting value is bound to the corresponding variable in the function (by copying the value into new memory)

If the function assigns values to its parameters, only its local variable is assignedβ€”that is, anything passed into a function call is unchanged in the caller's scope(outside of the function)

Changes are applied to the local variable, whose scope ends when the function returns

Example

class CallByValueTest {
    public static float incSquare(float x) {
        x = x + 1;
        return x * x;
    }

    public static void main(String args[]) {
        float x = 15;
        float y = incSquare(x);
        System.out.println(String.format("x = %s, y = %s", x, y));

        x = incSquare(x);
        System.out.println(String.format("x = %s", x));
    }
}

The above example can be run as

This shows that the value of variable x in main() function doesn't get changed after the function incSquare() is called with x as argument

The x parameter of incSquare() function gets the value of the variable x of main function, since Java is call by value

This parameter is incremented by 1 and its square value is returned, which as assigned to variable y

To change the value of variable x in main() function, it is assigned the value of incSquare() function, like y

cl-linux-java-call-by-value

Typically, arguments are passed by value and objects are passed by reference