A primitive type and complex type are different from each other primarily in the way data is stored. You're actually looking at the differences between a primitive type and a class type
1. Every variable is stored as a location in the computer memory.
The above statement applies to both primitive types and also class
types.
The differences:
2. For a primitive type: the value of the variable is stored in the memory location assigned to the variable.
That means if we assigned int x = 10
, the value of x
is stored in
where the value of 10
is stored, i.e the memory location. That means
when we "look" at x, '10' is stored there. Maybe it would help to
think of it more like an "assignment" where you command that x be
equal to 10.
3. For a class type: It only stores the memory address of the object that stores the value. It does not directly hold the
object itself.
Integer x = 10 will have a memory address that points to object of
type int, which will then hold the value of 10. This is known as a
reference. Think of it as directory that tells you to go to which shelf to actually retrieve the value.
Also
Class types are also known as reference types, or object types, that is they all mean an Object of a class (be it an Integer class, or MyPerson class).
Primitive types are not reference types because they do not hold references (memory addresses).
This distinction is the reason for "wrapper classes" in daily use, and types such as Integer
are seen as a wrapper class to an int
, to allow for data manipulation such as storing integers in a data structure such as an ArrayList. Because ints
a primitive data type, is not an object
, while Integer
is. Since primitive types are not objects, we have to put them into a class in order for us to add them to Lists, Dictionaries etc. This way we have a List of Objects (which, point to the primitive types) but they are not a naked primitive datatype by itself. See this SO question for further info
Additional reading on the difference between a primitive and non-primitive (aka Class/reference/object type) is detailed here. They have a nice diagram illustrating it too.