Monday, January 30, 2017

Call By Value V/S Call By Reference Java

Tags

Call by value: In this approach copy of the current variables are passed to called function.
i.e any change in called function on values is not reflected in main program...

Following code will illustrate this:

Code:
import java.util.*;
public class Value 
{

    public static void main(String[] nt) 
    {
       Scanner in=new Scanner(System.in);
       System.out.print("Enter A:");
       int a=in.nextInt();
       System.out.print("Enter B:");
       int b=in.nextInt();
       swap(a,b);
       System.out.println("After Swapping Outside Swap Function :");
       System.out.println("A:"+a);
       System.out.println("B:"+b);
    }
    public static void swap(int c,int d)
    {
        int temp=d;
        d=c;
        c=temp;
       System.out.println("After Swapping Inside Swap Function :"); 
        System.out.println("A:"+c);
        System.out.println("B:"+d);
    }
}

Output:


Call By Reference: As there are no pointers in java so we can not use & to refer to the variables

Following Code Will Illustrate this:

Code::

import java.util.*;
class Swap
{
    int a,b;
    public void swap(Swap s)
    {
        int temp=s.a;
        s.a=s.b;
        s.b=temp;
    }
}
public class Reference 
{

    public static void main(String[] nt) 
    {   Swap ob=new Swap();
        Scanner in=new Scanner(System.in);
       
        System.out.print("Enter A: ");
       ob.a=in.nextInt();
       System.out.print("Enter B: ");
       ob.b=in.nextInt();
       
       System.out.println("Before Swapping :");
       System.out.println("A:"+ob.a);
       System.out.println("B:"+ob.b);
       
       ob.swap(ob);
       
       System.out.println("After Swapping :");
       System.out.println("A:"+ob.a);
       System.out.println("B:"+ob.b);
        
    }   
}

Output::