10 Jul 2014

Pass by reference in JAVA methods

This post will deal with how the objects passed to a JAVA method will be accessed inside the method and what the method can actual do with the arguments and what it cannot do.

    Consider the following example:

/*
    This is a plane Java object we will be using to express how this object is referenced and how the        String inside this class will be accessed
*/

class Obj
{
    String strVal;

    public Obj()
    {
      
    }
  
    public Obj(String str)
    {
        this.strVal = str;
    }
  
    public String getStrVal()
    {
        return strVal;
    }

    public void setStrVal(String strVal)
    {
        this.strVal = strVal;
    }
  
}

/*
    This is the main class where we will be playing with Objects of Obj class to learn how Java considers the pass arguments. This class mainly tries to exchange the objects, inturn the strings the objects holder to swap the contents.
*/
public class PassByRef
{
   /*
      This method tries to swap the objects that are being passed as arguments to this method.
   */
    public void exchange(Obj objA1, Obj objB1)
    {
        Obj objTemp = new Obj();
        objTemp = objA1;
        objA1 = objB1;
        objB1 = objTemp;       




   













    }
    
  /*
     This method tries to swap the String in the passed arguments to this method.
  */
    public void exchangeString(Obj objA2, Obj objB2)
    {
        String strTemp = objA2.getStrVal();
        objA2.setStrVal(objB2.getStrVal());
        objB2.setStrVal(strTemp);




   













    }
  
    public static void main(String[] args)
    {
        Obj objA = new Obj("FirstString");
        Obj objB = new Obj("SecondString");




       














       PassByRef pbr = new PassByRef();
        pbr.exchange(objA, objB);



      













        
        System.out.println("String in objA="+objA.getStrVal()+" String in objB="+objB.getStrVal());
        pbr.exchangeString(objA, objB);
        System.out.println("String in objA="+objA.getStrVal()+" String in objB="+objB.getStrVal());
    }
}
   The output of the above program being as follows:

 String in objA=FirstString String in objB=SecondString
 String in objA=SecondString String in objB=FirstString


 In the above main method after initializing the objA and objB with String "FirstString" and "SecondString" respectively, we pass these objects into method exchange of class
PassByRef, here the method tries to change the object references that are passed to this method, but this will not be taken back to the calling method. So the new reference is not reflected in the method main.
Where as in the method exchangeString, the String contents of the object that is passed by main  is changed and the main method is referencing the same object, so the changed contents can be got from main.