Understanding primitives on the stack and heap
Java comes with a predefined set of primitive data types. Primitive data types are always in lowercase, for example, double
. Contrast primitives with their associated wrapper counterparts, which are classes in the API, have methods (primitives do not), and wrappers start with a capital letter, for example, Double
.
The primitive data types can be broken down into integral types (whole numbers), namely byte
, short
, int
, long
, and char
, and floating-point types (decimal numbers), namely float
, double
, and boolean
(true
or false
).
Primitives can be stored on both the stack and the heap. They are stored on the stack when they are local variables to methods, in other words, parameters to the method or variables declared inside the method itself. Primitives are stored on the heap when they are members of a class, that is, instance variables. Instance variables are declared within the class scope, in other words, outside all of the methods. Therefore, primitive variables declared within a method go on the stack, whereas instance variables go on the heap (inside the object).
Now that we understand where primitives are stored, let us turn our attention to storing objects.