Skip to main content

How is Java Pass By Value?

What are we passing?

 In any programming language, we need to call functions or methods. We "pass" the inputs and get the output. For example, to add two numbers, 3 and 5, we will pass those numbers and get 8 as output.

These inputs can be primitives(like above) which will represent simple types or Object References .

Object can represent complex types . Animals, Vehicles are examples. A Cat or Car has many properties and behavior.

How Methods are processed ?

In Java, for each method call, a stack is created. Program execution happens in the main stack and for each method call, a separate stack is created. Once the method is completed, stack goes out of scope and control comes back to the execution point in the main method call.

How simple and complex types are made available in Method call stacks?

For simple types, value is stored in the stack itself. For complex types, objects are stored in the heap and address is stored in the stack which points to a location in the heap.

Pass by Reference & Pass by Value

When you are passing variables from one method to the other by reference, we are actually passing the address of the variable. So any change made in the called method will affect the original value.

When you are passing variables from one method to the other by value, we are passing a copy of the value.

How is Java Pass by Value?

Simple Types:

Stack 1:

Method 1: int a=3;

doSomething(a);

Stack 2:
Method 2 : doSomething( int number)
 {
     number=number * number;

     return number;
  }

If there is a variable a=3 in one method and we pass a to another method.
In the new call stack, only the value of "a" is passed.

"number" will have the value of "a" and any change made to the "number" in the new call stack won't affect the value of "a" in the original method call.

Complex Types:

Stack 1:
Method 1: Cat a=new Cat("black");

 doSomething(a);

Stack 2:
Method 2 : doSomething( Cat cat)
 {
    // using value of address which was passed down.
     cat.setColor("white");
   
// created a new object and hence got the new address
   cat=new Cat("yellow");
   cat.setColor("blue");

  }

This is a bit tricky and has 2 parts. Here also, we are passing the value down to the new method.

Part 1
But for complex types, value is the ("copy of")address of the object in heap .If you change any properties, it will reflect in the original object. Color of the cat will be changed to white.

Part 2

We are just passing the "value"  of the address but not the "bucket" which is holding that value.
So even if we create a new object and set the color as yellow or blue, it won't have an effect in the original object.

"cat" is the "bucket" which holds the address of the object that was passed down. As long as it's holding the address of the object, we can make changes. But if we change it to anything new, it won't have an effect in the original object.




Comments