KnowledgeBoat Logo
|
LoginJOIN NOW

Computer Applications

How is call-by-value way of function invoking different from call-by-reference way ? Give appropriate examples supporting your answer.

User Defined Methods

1 Like

Answer

In call by value, the called function creates its own work copy for the passed parameters and copies the passed values in it. Any changes that take place remain in the work copy and the original data remains intact.

In call by reference, the called function receives the reference to the passed parameters and through these references, it accesses the original data. Any changes that take place are reflected in the original data.

This can be clearly understood by the example given below:

public class DemoFnCalls
{
    public static int x = 10 ; 
    public static int y = 20 ;
    
    public void DemoTest()  {   
        System.out.println("Values initially. x =" + x + ",  y =" + y);
        swapCallByValue(x, y);
        System.out.println("Values after swapCallByValue method. x =" 
                                + x + ", y =" + y) ;
        DemoFnCalls object1 = new DemoFnCalls( ) ; 
        swapCallByRef(object1);
        System.out.println ("Values after swapCallByRef method. x ="
                                + x + ", y =" + y) ;
    }

    public static void swapCallByValue(int a, int b)  {	  
        int tmp;	
        tmp = a;
        a = b;
        b = tmp;
        System.out.println("Values inside swapCallByValue method. x =" 
                                + a + ", y = " + b);
    }

    public static void swapCallByRef(DemoFnCalls obj)   {
        int tmp;
        tmp = obj.x; 
        obj.x = obj.y; 
        obj.y = tmp;
        System.out.println("Values inside swapCallByRef method. x =" 
                                + obj.x + ", y =" + obj.y);
    }
}

Answered By

2 Likes


Related Questions