← Back to Chapters

Call by Value in Java

? Call by Value in Java

? Quick Overview

In Java, all method arguments are passed using call by value. This means Java always passes a copy of the variable to a method, not the original variable itself.

? Key Concepts

  • Java does not support call by reference
  • Primitive values are copied to methods
  • Changes inside a method do not affect original variables
  • Object references are also passed by value

? Syntax / Theory

When a variable is passed to a method, Java creates a new copy of that variable. Any modification happens only on that copy.

? Code Example

? View Code Example
// Demonstrates call by value using primitive data type
class CallByValue {
static void change(int x) {
x = 50;
}

public static void main(String[] args) {
int a = 10;
change(a);
System.out.println(a);
}

?️ Live Output / Explanation

Output

10

The value of a remains unchanged because only a copy of a was passed to the change() method.

? Interactive Visualization

Click the buttons to trace exactly what happens to the variables in memory.

Main Method
a = 10
➡️
change(int x)
x = ?
State: Initial. 'a' is 10.

? Tips & Best Practices

  • Do not expect primitive values to change after method calls
  • Understand reference passing clearly when working with objects
  • Use return values to get updated data from methods

? Try It Yourself

  • Modify the method to return a value and assign it back
  • Try passing an object and change its fields
  • Observe behavior with arrays