Primitive vs Reference Types
TL;DR
- Primitive Types: Store the actual value directly in memory (usually on the Stack). There are 8 of them:
byte,short,int,long,float,double,boolean,char. - Reference Types: Store a reference (memory address/pointer) that points to an object stored elsewhere in memory (on the Heap). Arrays, Classes, Strings, and Interfaces are reference types.
Concept
In Java, every variable has a type. These types are strictly divided into two categories based on how they hold data in memory.
Primitive Types
Primitives are the building blocks of data manipulation. They are not objects, meaning they do not have methods or fields (you can’t do myInt.toString()).
Because they store raw values directly, they are extremely fast and memory-efficient.
| Type | Size | Default Value |
|---|---|---|
boolean | 1 bit | false |
byte | 8 bits | 0 |
short | 16 bits | 0 |
char | 16 bits | \u0000 |
int | 32 bits | 0 |
long | 64 bits | 0L |
float | 32 bits | 0.0f |
double | 64 bits | 0.0d |
Reference Types
Everything that is not one of the 8 primitive types is a reference type. A reference type variable doesn’t hold the actual data; it holds the memory address of the object located on the Heap. When you assign one reference variable to another, they both point to the same object in memory.
Examples
public class TypesExample {
public static void main(String[] args) {
// --- PRIMITIVES ---
int a = 10;
int b = a; // The VALUE '10' is copied
b = 20;
System.out.println(a); // Output: 10 (a is unaffected by b)
// --- REFERENCE TYPES ---
int[] arr1 = {1, 2, 3};
int[] arr2 = arr1; // The REFERENCE (memory address) is copied
arr2[0] = 99;
System.out.println(arr1[0]); // Output: 99 (arr1 and arr2 point to the same array!)
}
}
Interview Questions
Q: Can primitive types be null?
A: No. Primitive types cannot be null. They always have a default value if declared as a class field (e.g., 0 for int, false for boolean). If you need a nullable number or boolean, you must use their corresponding Wrapper Classes (e.g., Integer, Boolean).
Q: Where are primitive and reference types stored in memory?
A: - Primitive variables declared as local variables in a method are stored on the Stack.
- Reference variables declared as local variables are also stored on the Stack, but the actual objects they point to are stored on the Heap.
- Note: If a primitive is a field (instance variable) inside a class, it is stored on the Heap along with the object.
Q: What is the difference between == for primitives and reference types?
A: - For primitives, == compares the actual values (10 == 10 is true).
- For reference types,
==compares the memory addresses (whether they point to the exact same object in memory). To compare the meaningful content of two objects, you should use the.equals()method.