Saturday 27 April 2013

How Pass by Value works in Java ???

In Java Pass by Value is everywhere ... whenever you pass an argument to a method in Java it is passed as a value. 

In Java, the primitives datatypes as well as the Class objects are passed by value only. 
By value i mean a copy of the original.
Let's take up a small example ...

public int doSomething(int val1, int val2) {
      val1 += 5;
      val2 += 10;
      return val1 + val2;
}

public static void main(String... args) {
     int val1 = 5;
     int val2 = 10;
     System.out.println("val1 = " + val1 + " , val2 = " + val2);
     int val3 = doSomething(val1,val2);

    
System.out.println("val1 = " + val1 + " , val2 = " + val2 + " , val3 = " + val3);
}

 As you can see in this example the two syso's print the same value of val1 and val2 before and after they are passed to the doSomething()

Now, if we talk about Class Objects, a copy of the object is passed as an argument to the method and the original object remains unchanged.

No comments:

Post a Comment