share

Saturday, 17 January 2015

Call by value and call by reference in java

 In java there is only call by value is possible. We achieve call by reference
  using call by object in java. As example show below
 public class CallByValueVSCallByRef {
        int i=5;
        void call1(int i){
               i+=10;
               System.out.println("In call1 function="+i);
           }
       void call2(CallByValueVSCallByRef obj){
               obj.i+=10;
               System.out.println("In call1 function="+i);
           }
    public static void main(String[] args) {
        int i=10;
        CallByValueVSCallByRef obj=new  CallByValueVSCallByRef();
        obj.call1(obj.i);
        System.out.println("After call call1 i="+obj.i);
        obj.call2(obj);
        System.out.println("After call call2 i="+obj.i);
    }
   
}

===========================================
Output:
In call1 function=15
After call call1 i=5
In call1 function=15
After call call2 i=15

No comments:

Post a Comment