basically, how do i pass an integer variable by reference so I can change the value of the parameter variables after the function call.Code:void swap(int & a, int & b)
{
int temp;
temp = a;
a = b;
b = temp;
}
Printable View
basically, how do i pass an integer variable by reference so I can change the value of the parameter variables after the function call.Code:void swap(int & a, int & b)
{
int temp;
temp = a;
a = b;
b = temp;
}
There isn't that much difference between C and Java code.
Code:public void swap(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
That's not quite the same, because in that Java the values passed to the function will not be swapped.
The problem is that primative data types in Java (such as int) are not used as pointers, whereas classes are.
I believe there may be a library call, but if not you can wrap the values up as Integers (i.e. instances of the class Integer), pass these and unwrap, but that's a lot of extra code. I think Java 5 might do some of this for you with autoboxing, if you write a thing to swap two Objects.
Swapping mostly used in arrays, pass the array "By ref", and the locations of the two vars to be swaped
private void swap(int[] array,int locA,int locB){
int tmp=array[locA];
array[locA]=array[locB];
array[locB]=tmp;
}
thanks.