This confusion is very common and I don't even blame you for it. Well, let us break it down.
The contents of a primitive type are simply their associated values. For instance, if I say:
int x = 10;
Here, x
is allocated 4 bytes of memory and the value 10 is directly stored in that memory location.
You'll see all primitive type names are all lowercase in Java (int
, char
, double
and so on)
On the other hand, with reference types, the variable actually does not contain the value associated with it. In Java, String
s, Arrays and all library classes are reference types . Moreover, all user-defined types you create using classes are also reference types.
How are they different?
Let's look at arrays. If I say:
int[] array = new int[10];
Here, new int[10]
will allocate memory for 10 integers and it will not directly be stored in the variable array.
After allocating the memory, array
is assigned a value that is the memory location just allocated. That is array
does not actually contain the array of 10 integers but it contains the memory address/reference to that another memory location actually containing the 10 arrays.
Let's see in action how they work differently:
I'm creating two integers here:
int n1 = 5;
int n2 = n1;
n2 = n2 + 2;
You can see, first n1
is assigned as 5, then when I assign n2
, the value 5 is simply copied from n1
to n2
. When I do n2 = n2 + 2;
, the value of n2
becomes 7, but n1
does not change, it stays 5.
Now, about reference types:
int[] a1 = {1, 2, 3};
int[] a2 = a1;
a2[0] = a2[0] + 5;
I first create an array a1
, then I create a2
and assign it as a1
. Here's the fun part, when I assign a2
to a1
, the entire array is not copied to a2
, the memory location/reference pointing to that another memory location that contains the array is copied. You can see, I add 5 to a2[0]
that is, the first element 1. Now, a2[0]
becomes 6. Not just that, a1[0]
also becomes 6!
This is because both variables a1
and a2
are referring/pointing to the same memory location!
Hope this helps. If you have an more queries, let me know :)