The difference between Primitive and Reference type variables in Java

Supakon_k
2 min readFeb 5, 2023

--

Photo by Lex Sirikiat on Unsplash

You might wonder when you code in java and see these variables.

  • int
  • Integer
  • bool
  • Boolean

What’s the difference between them, and how to use them correctly? First, let’s talk about their definition between them.

Primitive Type

  • The primitive type is the variable that stores the actual value in the memory.

Reference Type

  • The reference type is a variable that stores the reference object in memory again.

After you understand the definition of those types now, let’s take a look at the benefit of understanding this concept.

For the benefit of memory efficiency

The primitive type stores actual value in the memory, so when you use the primitive type, you’ll gain more memory efficiency. In general, if you want to use it only to store and get the data, you should use primitive type. For example, it’s good to use primitive type when you create a small method to compute something to get the actual value that’s better for memory.

For the benefit of the complex data structure

The reference type treats like an object, so it can call methods on the reference type, for example,

when we declare an Integer variable. we can use the toString() method. In contrast, we can’t use the toString() method when we use the int variable.

It depends on your requirement, and you can mix the benefit of these variables into your project.

--

--