DEV Community

Chhavi Joshi
Chhavi Joshi

Posted on

Day 1, part II : Call by value

Earlier we talked about what functions are, how their syntax looks like and how they work, now let us dive a level deeper into it.

The functions in java are "call by value", which means that the value that we provide as argument is not directly given to the function but a copy of its value is given.

Lets understand it by example of swap function:

Output:

In this code we wrote the print statement inside the function itself so we got out desired result, but if we remove the print statement from the function and write

System.out.println("a = " + a + "b = " + b);
Enter fullscreen mode Exit fullscreen mode

in the main function instead, the code would show different behaviour, i.e. its original value would be displayed. Because what we sent in the function was a copy of actual variables and their scope lies inside the function only. So if we wrote the print statement outside the swap function the original value would be printed and not what we did to their copy

Top comments (0)