Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create an alias/reference of a variable (JAVA)

Tags:

java

reference

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 ?

like image 447
Arcyno Avatar asked Nov 04 '15 14:11

Arcyno


People also ask

How do you create an alias variable in Java?

public static void main(String[] args){ MyClass myObject = new MyClass(); ... int[] temp = myObject. getvariable(); // use of temp ... }

Does Java allow aliasing?

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.

What is an alias in Java?

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.


2 Answers

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.

like image 60
Paul Boddington Avatar answered Oct 22 '22 11:10

Paul Boddington


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.

like image 3
Aurasphere Avatar answered Oct 22 '22 12:10

Aurasphere