learn2code

Call by Value in Java Explained: How Java Passes Arguments

Java for Each Loop. Call by Value in Java and MCQ on Multithreading in Java and Design Patterns in Java and Strong Numbers in Java

Call by Value in Java is a widely-used programming language known for its simplicity, robustness, and platform independence. One of the fundamental concepts in Java is how it handles parameter passing. Java uses the “call by value” mechanism, which can be a source of confusion for many developers, especially those coming from languages that support “call by reference.” In this blog, we will delve into the concept of call by value in Java, understand how it works, differentiate it from call by reference, and explore practical examples to clarify the concept.

What is Call by Value in Java?

In Java, when a method is called, the arguments passed to the method are copied into the method’s formal parameters. This means that any changes made to the parameters within the method do not affect the original arguments. This mechanism of passing parameters is known as “call by value.”

Example:

public class CallByValueExample {
    public static void main(String[] args) {
        int num = 10;
        modifyValue(num);
        System.out.println("Value after method call: " + num);
    }

    public static void modifyValue(int n) {
        n = n + 10;
        System.out.println("Value inside method: " + n);
    }
}

Output:

Value inside method: 20
Value after method call: 10

In the example above, the value of num remains unchanged outside the method modifyValue because the parameter n is a copy of num.

How Call by Value Works

When a method is called, the following steps occur:

  1. The values of the arguments are copied into the formal parameters of the method.
  2. The method operates on the copied values.
  3. Any changes made to the parameters within the method do not affect the original arguments.

This behavior applies to both primitive data types and reference data types (objects).

Call by Value with Primitives

When dealing with primitive data types (int, float, double, etc.), call by value is straightforward. The value of the primitive is copied, and changes to the parameter do not affect the original value.

Example:

public class PrimitiveExample {
    public static void main(String[] args) {
        int a = 5;
        changePrimitive(a);
        System.out.println("After method call: " + a);
    }

    public static void changePrimitive(int num) {
        num = 10;
        System.out.println("Inside method: " + num);
    }
}

Output:

Inside method: 10
After method call: 5

In this example, the value of a remains 5 after the method call.

Call by Value with Objects

When it comes to objects, call by value can be a bit more complex. The reference to the object is passed by value, meaning that the method receives a copy of the reference. Although the reference itself is a copy, it still points to the same object in memory. Therefore, changes to the object’s fields within the method will affect the original object.

Example:

class Person {
    String name;

    Person(String name) {
        this.name = name;
    }
}

public class ObjectExample {
    public static void main(String[] args) {
        Person person = new Person("Alice");
        modifyObject(person);
        System.out.println("After method call: " + person.name);
    }

    public static void modifyObject(Person p) {
        p.name = "Bob";
        System.out.println("Inside method: " + p.name);
    }
}

Output:

Inside method: Bob
After method call: Bob

In this example, the name field of the person object is changed within the method, and this change is reflected outside the method because the reference points to the same object.

Call by Value vs. Call by Reference

The key difference between call by value and call by reference lies in how arguments are passed to methods:

  • Call by Value: A copy of the argument’s value is passed to the method. Changes to the parameter do not affect the original argument. Java uses call by value.
  • **

Call by Reference**: A reference to the actual argument is passed to the method. Changes to the parameter affect the original argument. Languages like C++ support call by reference.

Java’s call by value can sometimes give the illusion of call by reference when dealing with objects, but it’s important to remember that it’s always the reference that is passed by value, not the actual object.

Practical Examples

Let’s explore some practical examples to solidify our understanding of call by value in Java.

  1. Swapping Values: Attempting to swap values of primitives using a method.
public class SwapExample {
    public static void main(String[] args) {
        int x = 5;
        int y = 10;
        swap(x, y);
        System.out.println("After swap: x = " + x + ", y = " + y);
    }

    public static void swap(int a, int b) {
        int temp = a;
        a = b;
        b = temp;
        System.out.println("Inside swap: a = " + a + ", b = " + b);
    }
}

Output:

Inside swap: a = 10, b = 5
After swap: x = 5, y = 10

In this example, the values of x and y are not swapped because the method works with copies of the arguments.

  1. Modifying Object Fields: Changing the fields of an object within a method.
class Account {
    double balance;

    Account(double balance) {
        this.balance = balance;
    }
}

public class AccountExample {
    public static void main(String[] args) {
        Account acc = new Account(1000.0);
        deposit(acc, 500.0);
        System.out.println("After deposit: " + acc.balance);
    }

    public static void deposit(Account account, double amount) {
        account.balance += amount;
        System.out.println("Inside deposit: " + account.balance);
    }
}

Output:

Inside deposit: 1500.0
After deposit: 1500.0

In this example, the balance field of the acc object is updated within the method, and the change is reflected outside the method.

  1. Resetting Object Reference: Attempting to reset an object reference within a method.
class Car {
    String model;

    Car(String model) {
        this.model = model;
    }
}

public class ReferenceExample {
    public static void main(String[] args) {
        Car car = new Car("Toyota");
        resetCar(car);
        System.out.println("After reset: " + car.model);
    }

    public static void resetCar(Car c) {
        c = new Car("Honda");
        System.out.println("Inside reset: " + c.model);
    }
}

Output:

Inside reset: Honda
After reset: Toyota

In this example, the car reference within the method points to a new Car object, but this change does not affect the original car reference outside the method.

Conclusion

Understanding call by value in Java is crucial for writing effective and bug-free code. By recognizing that Java always passes arguments by value, whether they are primitives or references, you can predict the behavior of your methods and avoid common pitfalls. Remember that while the value of an object reference is passed to methods, the object itself is not copied, allowing you to modify the object’s state within the method.

You can download Java technical interview programming questions that were asked in Tech Mahindra, TCS, Wipro, Infosys, Accenture, Capgemini, and many other service and product-based companies.

Leave a Reply

Harish

Typically replies within a hours