Saturday 19 July 2014

Java is pass by value or pass by reference ?

Java is always pass by value only. The Java Spec says that everything in Java is pass-by-value. There is no such thing as "pass-by-reference" in Java.

Java manipulates objects data by reference. But Java doesn't pass method arguments by reference; it passes them by value. 

class Box{
 int width, height;
 
 static void swap(Box b1, Box b2){
  Box temp = b1;
  b1 = b2;
  b2 = b1;
 }
 
 Box(int width, int height){
  this.width = width;
  this.height = height;
 }
 
 public static void main(String args[]){
  Box b1 = new Box(5, 5);
  Box b2 = new Box(10, 10);
  
  System.out.println("Before swapping");
  System.out.print("for b1: width=" +b1.width);
  System.out.println(" height=" + b1.height);
  System.out.print("for b2: width=" +b2.width);
  System.out.println(" height=" + b2.height);
  
  swap(b1, b2);
  
  System.out.println("After swapping");
  System.out.print("for b1: width=" +b1.width);
  System.out.println(" height=" + b1.height);
  System.out.print("for b2: width=" +b2.width);
  System.out.println(" height=" + b2.height);
 } 
}

Output
Before swapping
for b1: width=5 height=5
for b2: width=10 height=10
After swapping
for b1: width=5 height=5
for b2: width=10 height=10

As you observe the output, the swap method doesn't swap the data since b1 and b2 are just references, Java passes the references by value just like any other parameter.  



                                                             Home

No comments:

Post a Comment