In C++, when a function takes an argument, there are three ways of passing an argument: passing by copy, passing by reference, and passing by pointer;The programmer may select the scheme at their choice. Java supports only the first two schemes with slightly different effects, and use of a scheme is tied to the type of the argument; if the argument is a primitive datum, passing by copy is implied; otherwise, passing by reference is assumed. Let’s see some examples here
- Passing by copy in C++
void swap(CBase a, CBase b)
{
CBase c = a;
a = b;
b = a;
}
This function has no effect on values of a and b.
- Passing by reference in C++
void swap(CBase &a, CBase &b)
{
CBase c = a;
a = b;
b = c;
}
On return, values of a and b are swapped.
- Passing by copy in Java
void swap(int a, int b)
{
int c = a;
a = b;
b = a;
}
This function has no effect on values of a and b;
- Passing by reference in Java
void swap(CBase a, Cbase b)
{
CBase c = a;
a = b;
b = c;
}
This function has no effect on values of a and b.
according to your last line, you can;t swap two objects in Java…?
Sorry, to clarify, the swap fucion does not change the values of a and b outside of the method.