Java implementation of a call by value
KW.java
class KW
{
    public static int add(int a,int b)
    {
        a=100;
        b=100;
        int c=a+b;
        return c;
    }
    public static void main(String args[])
    {
        int a=20,b=10,c;
        c=a+b;
        add(a,b);
        System.out.println(a+b);
    }
}
Output
kodingwindow@kw:~$ javac KW.java
kodingwindow@kw:~$ java KW 30 kodingwindow@kw:~$
Java implementation of a call by value by passing object as a value
KW.java
class KW
{
    int a=100,b=100;
    public void add(KW k)
    {
        k.a=k.a+k.b+500;
    }
    public static void main(String args[])
    {
        KW k=new KW();
        k.a=k.a+k.b;
        System.out.println(k.a);
        k.add(c);
        System.out.println(k.a);
    }
}
Output
kodingwindow@kw:~$ javac KW.java
kodingwindow@kw:~$ java KW 200 800 kodingwindow@kw:~$
Advertisement