Introduction
Java provides powerful tools to store and manage data efficiently. Among them, Collections, ArrayList, and Wrapper Classes play a very important role in real-world applications.
In this blog, we will understand:
- What is Collection in Java
- What is ArrayList
- What are Wrapper Classes
- How Integer and Wrapper objects are stored in Java memory
What is Collection in Java?
The Collection Framework in Java is a set of classes and interfaces used to store and manipulate groups of objects.
It provides:
- Dynamic data storage
- Built-in methods (add, remove, search)
- Better performance and flexibility
Some common collection types:
- List (ArrayList, LinkedList)
- Set (HashSet)
- Map (HashMap)
What is ArrayList?
ArrayList is a class in Java that implements the List interface.
Key Features:
- Dynamic size (can grow and shrink)
- Maintains insertion order
- Allows duplicate elements
Example:
import java.util.*;
ArrayList<Integer> list = new ArrayList<>();
list.add(10);
list.add(20);
list.add(30);
Unlike arrays, ArrayList does not have a fixed size.
What is a Wrapper Class?
Java provides wrapper classes to convert primitive data types into objects.
Example:
- int → Integer
- char → Character
- double → Double
Example:
int a = 10;
Integer obj = a; // Autoboxing
Why Wrapper Classes?
- Collections can store only objects
- So primitive types must be converted into objects
Autoboxing and Unboxing
- Autoboxing → primitive to object
- Unboxing → object to primitive
Integer obj = 10; // Autoboxing
int num = obj; // Unboxing
How Data is Stored in Java Memory?
Java mainly uses two types of memory:
1. Stack Memory
- Stores primitive variables
- Stores reference variables
- Fast access
Example:
int a = 10;
a is stored in stack
🔹 2. Heap Memory
- Stores objects and instances
- Managed by JVM
Example:
Integer obj = new Integer(10);
Object is stored in heap, reference is in stack
Integer & Wrapper Storage in Memory
Case 1: Primitive int
int a = 10;
Value 10 stored directly in stack memory
Case 2: Wrapper Integer
Integer obj = 10;
What happens:
- Object created in heap memory
- Reference stored in stack memory
Case 3: ArrayList Storage
ArrayList<Integer> list = new ArrayList<>();
list.add(10);
Internally:
- ArrayList object → stored in heap
- Integer objects → stored in heap
- Reference → stored in stack
Key Difference
| Type | Stored In |
|---|---|
| int (primitive) | Stack |
| Integer (object) | Heap |
| ArrayList | Heap |
Why This is Important?
Understanding memory helps in:
- Writing efficient code
- Avoiding memory issues
- Improving performance
Top comments (0)