posted 25 years ago
hmehta,
In Java, arguments get passed to methods by VALUE, not by reference. This includes primitive types like int, as well as objects.
You sound like you know some C++, so I will try to explain it from that perspective. Look at the C++ code below:
#include "stdafx.h"
#include "iostream.h"
// passing by value
void swap1(int a, int b) { int temp = a; a = b; b = temp;}
// passing by reference
void swap2(int &a, int &b) { int temp = a; a = b; b = temp;}
int main(int argc, char* argv[])
{
int x = 5;
int y = 10;
cout << "before first swap, x = "
<< x << ", y = " << y << endl;
swap1(x, y);
cout << "after first swap, x = "
<< x << ", y = " << y << endl;
cout << "before second swap, x = "
<< x << ", y = " << y << endl;
swap2(x, y);
cout << "after second swap, x = "
<< x << ", y = " << y << endl;
return 0;
}
swap1() passes by value, so the values of x and y do NOT change. swap2() passes by reference, so the values of x and y DO change.
In Java, this is not an option. It is ALL pass-by-value. If you want your method to ACT like pass-by-reference, you need to use the trick with the one-element arrays from the earlier post.
Does this make more sense to you?
Stephanie