• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Reference Types vs Primitive Types - Java

Sascha Оффлайн

Sascha

Заместитель Администратора
Команда форума
Администратор
Регистрация
9 Май 2015
Сообщения
1,483
Баллы
155

Example


Let's say you create an array in Java:


int[] array1 = {1, 2, 3, 4, 5};




Now, we have our variable array1 that holds our

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

. You decide to create a second variable called array2, and you set it equal to array1.


int[] array2 = array1;




If we print our two arrays, we expect to get the same content, and that is what actually happens.


>>> [1, 2, 3, 4, 5]
>>> [1, 2, 3, 4, 5]




But, what if you want to change a number in array1?, let's change our second index (number 3) to 9.


array1[2] = 9;




Again, let's print our two arrays.


>>> [1, 2, 9, 4, 5]
>>> [1, 2, 9, 4, 5]




Wow, why our second array has the number 9 as well?

This is the time when we have to look at the

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

, more specifically, the Stack and the Heap.

In java, data is classified in Reference and Primitive types, let's first look at how primitive types are saved in memory.

Primitive Types


Java supports eight primitive data types, which you can see

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

, i'll be using int for the demo.
So imagine, we have the following code:


int x = 12;
int y = x;




Since these are primitive data types, both the variable and the value are saved on the stack, so when you declared y to be equal to x, what is going to happen is that the value from x will get copied, and it will be saved in y, in this case each variable has its own value now. If you wanted to change the value of y, you would only be modifying that value for that variable.


y = 30;




Below, you have the visual representation:


Reference Types


Reference types hold references to objects and provide access to those objects stored somewhere in memory allocated on the heap, there are four kinds of

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

.

Let's go back to our example and explain it:


int[] array1 = {1, 2, 3, 4, 5};
int[] array2 = array1;




So, what's happening here?, as mentioned before, reference types hold references to the object, in this case, an array. The variable array1 is holding a reference in the stack, the variable is saved but this time, with the reference (imagine the reference as an arrow pointing to the object). As it happened before with primitive types, it copied the value from the variable to another, in this case the value we are copying is a reference, so now both array1 and array2 are pointing to the same object on the heap, that's why any change to one of the variables will reflect on the other.
Let's create an array just for array2:


array2 = new int[5]; // Array of size 5
array2[1] = 9; // Updating the value of index 1




Now, array2 is pointing to a totally different object, and it's no longer pointing to the same object as array1, when we now update a value of array2, it won't affect array.

Below, you have the visual representation:


And that's all! Hope you enjoyed this little post.



Источник:

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу