Thursday, April 21, 2011

Passing by value vs pass by reference

Argument Passing
When a simple type is passed to a method, it is done by use of call-by-value. Objects are passed by use of call-by-reference.
So when object is passed,  it is passed as reference.

Returning objects
Let Test be a class, and

class Test {
    int a;
      Test(int i) {
          a = i;
       }
   Test increase {
    Test temp = new Test(a+10);
    return temp;
  }
}


As you can see, each time increase( ) is invoked, a new object is created, and a
reference to it is returned to the calling routine.
The preceding program makes another important point: Since all objects are
dynamically allocated using new, you don’t need to worry about an object going
out-of-scope because the method in which it was created terminates. The object will
continue to exist as long as there is a reference to it somewhere in your program.
When there are no references to it, the object will be reclaimed the next time garbage
collection takes place.
Java supports recursion.




No comments:

Post a Comment

Chitika