I have used a lot of C++ and I am quite confused with the way Java works : if I have a class
public class MyClass{
private int[] myVariable;
...
public int[] getVar(){
return myVariable;
}
}
and then I want to use my variable elsewhere :
public static void main(String[] args){
MyClass myObject = new MyClass();
...
int[] temp = myObject.getvariable();
// use of temp
...
}
is temp a copy or a reference of myVariable ?
How do you get a copy / a reference to it ?
public static void main(String[] args){ MyClass myObject = new MyClass(); ... int[] temp = myObject. getvariable(); // use of temp ... }
Conclusion. Alias is used in Java when the reference of more than one is linked to the same object. The drawback of aliasing is when a user writes to a specific object, and the owner for some other references does not guess that object to change.
Aliasing means that more than one reference is tied to the same object, as in the preceding example. The problem with aliasing occurs when someone writes to that object.
There is only one int[]
in your example. There is no copying at all. What is returned by the method getVar
is a reference to the object.
After the line
int[] temp = myObject.getvariable();
both temp
and myVariable
are references to the same object. You can test this by doing e.g. temp[0] = 9;
. The change will be visible in both places.
If you want to copy an array, you can use one of array.clone()
, Arrays.copyOf(array, array.length)
or System.arraycopy(...)
but none of these are used in your example.
That gets you confused because unlike C, Java is only pass-by-value. So you won't have a reference to that object but only a copy and then if you make any modification to that variable the original won't be affected. See this question for more details: Is Java "pass-by-reference" or "pass-by-value"?
EDIT
To be more specific, in your example you will actually get a reference to the array. But still, that's not like a C pointer. You get a reference only because the actual value you are copying it's a reference itself. As I said, you may find a more detailed explanation about this on the link above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With