Wednesday, 23 January 2013

PASS BY VALUE OR PASS BY REFERENCE IN JAVA:


Java doesn't pass method arguments by reference; it passes them by value.

public void testSwap( Sample s1, Sample s2){
  
           s1.x = 100;
           s1.y = 100;
           Sample temp = s1;
           s1 = s2;
          s2 = temp;
}


public static void main(String [] args)
{
  Sample s1 = new Sample(0,0);
  Sample s2 = new Sample(0,0);
  ("X: " + s1.x + " Y: " +s1.y);
  System.out.println("X: " + s2.x + " Y: " +s2.y);
  System.out.println(" ");
  testSwap (s1 ,s1);
  System.out.println("X: " + s1.x + " Y:" + s1.y);
  System.out.println("X: " + s2.x + " Y: " +s2.y);
}

The method successfully alters the value of s1, even though it is passed by value; however, a swap of s1 and s2 fails! This is the major source of confusion. In the main() method, s1 and s2 are nothing more than object references. When we pass s1 and s22 to the testSwap() method, Java passes the references by value just like any other parameter. This means the references passed to the method are actually copies of the original references.


Only the method references are swapped, not the original ones.