Java - Call by value

Java

Share

In this tutorial we will learn about call by value in Java programming language.

In Java any primitive value that we pass to a method of a class is actually passed by value. Meaning, any change made in the called method is not reflected back in the calling method.

Example

In the following example we have the Addition class having add100 method which adds 100 to a passed value.

class Addition {
  public void add100(int n) {
    System.out.println("In add100() method of Addition class.");
    System.out.println("Value of n before addition: " + n);
    n = n + 100;
    System.out.println("Value of n after addition: " + n);
    System.out.println("Returning back to the calling method.");
  }
}

public class Example {
  public static void main(String[] args) {

    // create an object
    Addition obj = new Addition();

    // variable
    int n = 10;

    System.out.println("In main() method of Example class.");
    System.out.println("Value of n before call: " + n);

    // pass an integer value
    System.out.println("Passing value of n to add100() method of Addition class.");
    obj.add100(n);
    System.out.println("Back from add100() method of Addition class.");

    System.out.println("In main() method of Example class.");
    System.out.println("Value of n after call: " + n);

  }
}

Output:

$ javac Example.java 
$ java Example
In main() method of Example class.
Value of n before call: 10
Passing value of n to add100() method of Addition class.
In add100() method of Addition class.
Value of n before addition: 10
Value of n after addition: 110
Returning back to the calling method.
Back from add100() method of Addition class.
In main() method of Example class.
Value of n after call: 10

In the above example we are passing value 10 to the add100() method of the Addition class from the main() method of the Example class.

Inside the add100() method we are adding 100 to the value of n.

When we return back from the called method add100() to the calling method main() the value of n remains the same i.e. 10.

So, we can tell that when we are passing value to a method we are actually passing a copy and any change made inside the called method is not reflected back. And this is call by value.

Share