Primitives and Objects in Java Memory
In Chapter 1, we saw the differences between primitives, objects, and references. We learned that primitives are types that come with the Java language; in other words, we do not have to define primitive types, we just use them. For example, int x;
defines (creates) a primitive variable, x
, which is of (the primitive) type int
. This means that x
can store whole integer numbers only, for example, -5, 0, 12, and so on.
We also learned that objects are instantiations of a class and that we use the new
keyword to create instances of objects. For example, assuming a Person
class exists, new Person();
instantiates (creates) an object of type Person
. This object will be stored on the heap.
We saw that references enable us to manipulate objects and that references are of four different types: class
, array
, interface
, and null
. When you create an object, the reference to the object is what you receive back. For example, in the code Person p = new Person();
, the reference is p
and it is of type Person
. Whether the reference is placed on the stack or on the heap depends on the context – more on this later.
Understanding the differences between references and objects is very important and greatly simplifies core object-oriented programming (OOP) concepts, such as inheritance and polymorphism. This also helps in fixing ClassCastException
errors. Being aware of Java’s call-by-value mechanism and, in particular, how it relates to references can prevent subtle encapsulation issues known as escaping references.
In this chapter, we will delve more deeply into the following topics:
- Understanding primitives on the stack and heap
- Storing objects on the heap
- Managing object references and security