Java Call by Value and Call by Reference

    Call by Value and Call by Reference

    Java only supports the call by value but not the call by reference. The call by value means that you are calling a method by passing it a value. The value will only get changed in the called method and is remain unaffected in the calling method.

    Call by value: Example-

    class Simple{  
     int var=50;  
    
     void method_call(int var){  
     var=var+100;
     }  
    
     public static void main(String args[]){  
       Simple op=new Simple();  
    
       System.out.println("before change "+op.var);  
    
       op.method_call(500);  
    
       System.out.println("after change "+op.var);  
    
     }  
    }  

    Output-

    Call by value by passing the class reference-

    class Simple{  
     int var=50;  
     void method_call(Simple op){  
     op.var=op.var+100;
     }  
    
     public static void main(String args[]){  
       Simple op=new Simple();  
    
       System.out.println("before change "+op.var);  
    
       op.method_call(op);  
    
       System.out.println("after change "+op.var);  
    
     }  
    } 

    Output-