What are pass by reference and pass by value?

Solution:

When an object is passed by value, this means that a copy of the object is passed. Thus, even if changes are made to that object, it does not affect the original value. When an object is passed by reference, this means that the actual object is not passed, rather a reference of the object is passed. Thus, any changes made by the external method, are also reflected in all places.

Sample code is presented below which shows pass by value.

Pass by Value

public class ComputingEngine 
{ 
    public static void main(String[] args) 
    { 
        int x = 15;
        ComputingEngine engine = new ComputingEngine();
        engine.modify(x); 
        System.out.println("The value of x after passing by value "+x); 
    } 
    public  void modify(int x) 
    { 
        x = 12; 
    } 
}

Below example shows pass by reference in the code.

public class ComputingEngine 
{ 
    public static void main(String[] args) 
    { 
       
        ComputingEngine engine = new ComputingEngine();
       
      
        Computation computation = new Computation(65);
        engine.changeComputedValue(computation);
       
        System.out.println("The value of x after passing by reference "+ computation.x);
       
    } 
   
   
   
    public void changeComputedValue(Computation computation)
    {
        computation = new Computation();
        computation.x = 40;
    }
}
 
 
class Computation 
{ 
    int x; 
    Computation(int i) { x = i; } 
    Computation()      { x = 1; } 
}
0 answers