Java-Call by Value and Call by Reference

Call by Value

In Java, when you pass a primitive type to a method, it is passed by value. Thus, what occurs to the parameter that receives the argument has no effect outside the method. For example, In the following program, the operations that occur inside changeData( ) have no effect on the values da1 and da2 used in the call; their values here did not change to 40 and 40.

Program

Call by Reference

When you pass an object to a method, the situation changes dramatically, because objects are passed by what is effectively call-by-reference. Keep in mind that when you create a variable of a class type, you are only creating a reference to an object. Thus, when you pass this reference to a method, the parameter that receives it will refer to the same object as that referred to by the argument. This effectively means that objects are passed to methods by use of call-by-reference. Changes to the object inside the method do affect the object used as an argument. For example, In the following program, the actions inside changeData( ) have affected the object used as an argument.

Program

 

Program Source Call by Value

class Data {
   
    void changeData(int da1,int da2)
    {
        da1+=20;
        da2+=20;
    }
}

public class Javaapp {
    
    public static void main(String[] args){
        
        int data1 = 20,data2 = 20;
        System.out.println("data1 = "+data1);
        System.out.println("data2 = "+data2);
        
        Data dataobj = new Data();
        dataobj.changeData(data1, data2);
        System.out.println("After dataobj.changeData()");
        System.out.println("data1 = "+data1);
        System.out.println("data2 = "+data2);
   }
}

Program Source Call by Reference

class Data {
    
    int data1 = 20;
    int data2 = 20;
    
    void changeData(Data obj,int da1,int da2)
    {
        obj.data1+=da1;
        obj.data2+=da2;
    }
}

public class Javaapp {
    
    public static void main(String[] args){
       
        Data dataobj = new Data();
        System.out.println("dataobj.data1 = "+dataobj.data1);
        System.out.println("dataobj.data2 = "+dataobj.data2);
        dataobj.changeData(dataobj, 20, 20);
        System.out.println("After dataobj.changeData()");
        System.out.println("dataobj.data1 = "+dataobj.data1);
        System.out.println("dataobj.data2 = "+dataobj.data2);
   }
}

Leave a Comment