Call by value and Call by reference in java

call-by-value-and-call-by-reference-in-java


Call By Value in Java


In call by value method the value will not change or affected in the called method.
/**
 * class CallByValue
 * InspireSkills : Khurshid MD Anwar
 * Pure Function
 *
 */
public class CallByValue
{
    int a,b;
 
    void show(int x, int y)
    {
        a=x+2;
        b=y+2;
    }
    public static void main(String args[])
    {
        CallByValue ob=new CallByValue();
        int a, b;
        a=5;
        b=6;
        System.out.println("a=" + a);
        System.out.println("b=" + b);
        ob.show(a,b);
        System.out.println("a=" + a);
        System.out.println("b=" + b);
    }
}
Output
a=5
b=6
a=5
b=6

Call By Reference in Java

In call by reference values will change in the called method.
/**
 *class CallByReference
 *
 * @InspireSkills: Khurshid MD Anwar
 * Impure Function
 */
public class CallByReference
{
    int a,b;
 
    void show(CallByReference x)
    {
        a=a+2;
        b=b+2;
    }
    public static void main(String args[])
    {
        CallByReference ob=new CallByReference();
     
        ob.a=5;
        ob.b=6;
        System.out.println("a="+ob.a);
        System.out.println("b="+ob.b);
        ob.show(ob);
        System.out.println("a="+ob.a);
        System.out.println("b="+ob.b);
    }
}

Output 
a=5
b=6
a=7
b=8

Here two type of methods, one is Call by value where values passed as primitive data type and it is not change when it is call but in Call by reference the value as a reference or object and it change the original values.

More program



SHARE THIS
Previous Post
Next Post