Reputation: 28841
For the following code:
User myUser = new User();
User[] array1 = new User[10];
User[] array2 = new User[10];
array1[5] = myUser;
array2[5] = myUser;
Is the object myUser stored twice, or is only the address of the object stored on each of the objects?
Also does this still hold if i start messing around with the variable like:
temp = myUser;
array2[4] = temp;
Also if i make a change to myUser in one array, does it make the change to the other array?
EDIT: last question how would one store it by value instead of reference?
Upvotes: 1
Views: 1311
Reputation: 43023
Yes, only the reference to the User
object is stored in the array. Each of the reference points to the same object. Modifying the object through either of the arrays will modify the same one object.
The same applies to storing the refernce in variables as in your second example.
Only primitive types are stored by value, e.g. int
, boolean
, char
. Note that they also have corresponding reference type, e.g. for int
you have Integer
.
Upvotes: 4