What is the call by value method in Java?
Overview
In Java, we use the call by value method to pass the arguments to a function where the variable's value is passed. The function then uses that value to perform its operations. When the function is finished, the original variable is not affected by any changes made to the copy within the function.
Code
class Test {public static void main(String[] args) {int i = 1;fun(i);System.out.println("In main(): "+i);}static void fun(int j) {System.out.println("Inside fun():\nBefore Changing value: j = " + j);j = 2;System.out.println("After changing value: j = " + j);}}
Explanation
As we can see from the output, even though the value of i is changed inside the fun() method, it doesn't affect the value of i in the main() method. This is because Java uses the call by value to pass arguments.
This means that a copy of the variable is made and passed to the function. Therefore, any changes made to the variable inside the function will not affect the original variable.