Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java

What is the call by value method in Java?

Tarun Telang

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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);
}
}
Java code example for call by value

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.

Visualization of the call stack for the above Java code

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.

RELATED TAGS

java

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring