top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Pass By Value and Call By Reference in Java

Introduction 

One of the center ideas of writing computer programs is passing values to strategies and capabilities. Passing values in Java might be finished in one of two ways: by value or by reference. It's fundamental to grasp the distinctions between these two methods to compose successful and blunder-free code. In this post, we will examine pass by value and call by reference in Java, using examples, screenshots, and graphics to aid comprehension.

Overview 

Pass by value and call by reference are different strategies for passing arguments to methods. A reference to the original variable is supplied during a call by reference, but during a pass by value, a copy of the value is sent to the function. By default, Java utilizes a pass by value, which implies that the method receives a copy of the data. 

Example of call by value in Java 

We should begin by looking at an illustration of pass by value in Java. Consider about the accompanying code scrap:

java
public class PassByValueExample { 
    public static void main(String[] args) { 
        int number = 10; 
        System.out.println("Before calling the method: " number); 
        increment(number); 
        System.out.println("After calling the method: " number); 
    } 
     
    public static void increment(int num) { 
        num ; 
        System.out.println("Inside the method: " num); 
    } 
}  

In the above example, the increment method adds one to the value of the integer input num. The output is as follows when the increment method is used with the number variable as an argument:

SQL
Before calling method: 10 
Inside the method: 11 
After calling method: 10  

We can observe from the result that the method call has not affected the number's value. This exemplifies Java's usage of pass by value, which involves passing the method a copy of the value.

Pass by Value in Java 

Pass by value alludes to the most common way of reordering the contention's worth to the technique. The technique's underlying variable is unaffected by any progressions made to the contention. Let's examine another example to illustrate pass by value in Java: 

java
public class PassByValueExample { 
    public static void main(String[] args) { 
        int number = 10; 
        System.out.println("Before calling the method: " number); 
        changeValue(number); 
        System.out.println("After calling the method: " number); 
    } 
     
    public static void changeValue(int num) { 
        num = 20; 
        System.out.println("Inside the method: " num); 
    } 
}  

In this outline, the function changeValue acknowledges the number boundary num and gives it another worth. The result of running the code is as per the following:

SQL
Before calling method: 10 
Inside the method: 20 
After calling method: 10  

Once again, we can see that the original variable number remains unchanged after the method call. This behavior confirms that Java uses pass by value. 

Pass by Reference - Not supported by Java. 

As opposed to a few other programming languages, for example, C, Java doesn't unequivocally give pass by references. At the point when a technique utilizes pass by reference, it gets a reference to the first factor, empowering changes performed inside the strategy to affect the first factor. Java, however, treats references another way.

How Java Handles Pass by Reference Using Pass by Value? 

Java manages references through pass by value despite the fact that it doesn't unequivocally permit pass by reference. This infers that an item reference is duplicated and provided as a parameter at whatever point an object reference is passed to a technique. Thus, changes made to the reference inside a technique affect the first reference.

Think about the following instance: 

java
public class PassByValueExample { 
    public static void main(String[] args) { 
        StringBuilder sb = new StringBuilder("Hello"); 
        System.out.println("Before calling the method: " sb); 
        appendText(sb); 
        System.out.println("After calling the method: " sb); 
    } 
     
    public static void appendText(StringBuilder text) { 
        text.append(" World!"); 
        System.out.println("Inside the method: " text); 
    } 
}  

The function appendText in this example appends " World!" to a StringBuilder object that it receives as an argument. Running this code produces the following results:

SQL
Before calling the method: Hello 
Inside the method: Hello World! 
After calling the method: Hello World!  

The result demonstrates how the appendText method's modifications to the text reference have an impact on the original object. It's crucial to remember that the reference was supplied by value, though.

Case with Primitive Data Types 

Pass by value is simple to use when working with primitive data types in Java, such as int, float, or boolean. The primitive variable's value is copied and sent to the method. The method's initial variable is unaffected by any changes made to the argument.

Let's consider an example with primitive data types: 

java
public class PassByValueExample { 
    public static void main(String[] args) { 
        int num = 5; 
        System.out.println("Before calling the method: " num); 
        multiplyByTwo(num); 
        System.out.println("After calling the method: " num); 
    } 
     
    public static void multiplyByTwo(int number) { 
        number *= 2; 
        System.out.println("Inside the method: " number); 
    } 
}  

The output of running this code is as follows: 

SQL
Before calling method: 5 
Inside the method: 10 
After calling method: 5  

As expected, the original variable num remains unchanged after the method call. 

Pass by Value Using Java Primitive Types 

To further illustrate pass by value with primitive types, let's examine another example: 

java
public class PassByValueExample { 
    public static void main(String[] args) { 
        int a = 10; 
        int b = 20; 
        System.out.println("Before calling the method: a = " a ", b = " b); 
        swap(a, b); 
        System.out.println("After calling the method: a = " a ", b = " b); 
    } 
     
    public static void swap(int x, int y) { 
        int temp = x; 
        x = y; 
        y = temp; 
        System.out.println("Inside the method: x = " x ", y = " y); 
    } 
}  

The output of running this code is as follows: 

less
Before calling the method: a = 10, b = 20 
Inside the method: x = 20, y = 10 
After calling the method: a = 10, b = 20  

Again, we can observe that the original variables a and b remain unchanged after the method call. This demonstrates that Java uses pass by value even with primitive types. 

Pass by Value Using Java Objects 

When it comes to objects in Java, pass by value works slightly differently. A duplicate of the item reference is provided to the technique instead of the total item itself. This suggests that changes to the item's properties finished inside the technique will affect the first article.

java
public class PassByValueExample { 
    public static void main(String[] args) { 
        Person person = new Person("John"); 
        System.out.println("Before calling the method: " person.getName()); 
        changeName(person); 
        System.out.println("After calling the method: " person.getName()); 
    } 
     
    public static void changeName(Person p) { 
        p.setName("Jane"); 
        System.out.println("Inside the method: " p.getName()); 
    } 
} 
 
class Person { 
    private String name; 
     
    public Person(String name) { 
        this.name = name; 
    } 
     
    public String getName() { 
        return name; 
    } 
     
    public void setName(String name) { 
        this.name = name; 
    } 
}  

In this illustration, a Person class with a name attribute is present. A Person object is sent to the changeName function, which changes the name to "Jane." Running this code produces the following results:

SQL
Before calling the method: John 
Inside the method: Jane 
After calling the method: Jane  

As we can see, the changes made to the name property within the change name method affect the original Person object. 

Pass by Value for non-primitives 

While relegating another object reference inside the technique affects the first reference, changes to the item's properties are reflected in the first object.

Think about the following instance: 

java
public class PassByValueExample { 
    public static void main(String[] args) { 
        StringBuilder sb = new StringBuilder("Hello"); 
        System.out.println("Before calling the method: " sb); 
        assignNewObject(sb); 
        System.out.println("After calling the method: " sb); 
    } 
     
    public static void assignNewObject(StringBuilder text) { 
        text = new StringBuilder("Hi"); 
        System.out.println("Inside the method: " text); 
    } 
}  

The output of running this code is as follows: 

SQL
Before calling the method: Hello 
Inside the method: Hi 
After calling the method: Hello  

From the output, we can see that although the text reference within the assignNewObject method points to a new StringBuilder object, the original reference sb remains unchanged. 

Conclusion 

Understanding pass by value and call by reference in Java is crucial for writing effective and reliable code. Copy values are sent to methods by default in Java's pass by value technique. Although Java does not natively enable pass by references, it uses pass by values to manage object references. While assigning a new object reference has no effect on the original reference, changes made to an object's properties within a method do. 

By grasping the concepts of pass by value and call by reference, developers can design their code more accurately and avoid potential pitfalls. 

FAQs 

1: Can Java pass variables by reference? 

A: No, Java does not support pass by reference directly. It uses pass by value, even when dealing with objects. However, changes made to object properties within a method will affect the original object. 

2: Why does Java use pass by value? 

A: Java uses pass by value to ensure predictable behavior and avoid unintended side effects. By passing copies of values to methods, it maintains encapsulation and helps prevent modifications to variables outside the intended scope. 

3: Can I modify an object passed to a method in Java? 

A: Yes, you can modify an object's properties within a method in Java. However, assigning a new object reference within the method does not affect the original reference. 

4: What are the benefits of pass by value in Java? 

A: Pass by value promotes encapsulation, prevents unintended modifications to variables, and improves code clarity and predictability. It ensures that modifications made within a method do not affect the original variables outside the method's scope. 

Leave a Reply

Your email address will not be published. Required fields are marked *