Friday, June 10, 2011

Pass a array by reference to a method in java

Well what happens if you do something like this

void method1(){
int array[] = {3,4,33,22};
method2(array);
}

void method2(int array[]){
// modify array contents
}

The modifications that you do inside method2 wont reflect once the method returns. So how you make the changes that happen inside method2 to reflect in method1 even after it returns ? Well the answer in C/C++ would be to pass by reference. But how do you do that in java? Here's the trick. You actually wrap the int array inside a object and pass the objectname.arrayname to the method.

class intarray{
int array[] = {3,4,33,22};
}


void method1(){
intarray object = new intarray();
method2(objectarray);
}

void method2(int array[]){
// modify array contents
}

So in this case whatever you do to the array from method2 once it returns the changes are seen in method1 as well.

No comments:

Post a Comment