Heap memory in Java - Time & Space Complexity
When working with heap memory in Java, it's important to understand how the program's speed changes as it uses more memory.
We want to see how the time to allocate and manage memory grows as the program runs.
Analyze the time complexity of creating objects stored in heap memory.
public class Example {
public static void main(String[] args) {
int n = 1000;
MyObject[] arr = new MyObject[n];
for (int i = 0; i < n; i++) {
arr[i] = new MyObject(i);
}
}
}
class MyObject {
int value;
MyObject(int value) {
this.value = value;
}
}
This code creates an array of objects, each stored in heap memory, one by one.
Look for repeated actions that take time.
- Primary operation: Creating a new object in each loop cycle.
- How many times: The loop runs n times, creating n objects.
As the number of objects n increases, the time to create them grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 object creations |
| 100 | 100 object creations |
| 1000 | 1000 object creations |
Pattern observation: Doubling n doubles the work because each object creation takes roughly the same time.
Time Complexity: O(n)
This means the time to create objects grows in a straight line with the number of objects.
[X] Wrong: "Creating objects in heap memory is instant and does not affect program speed."
[OK] Correct: Each object creation takes time and memory allocation, so more objects mean more time spent.
Understanding how heap memory allocation affects time helps you write efficient programs and answer questions about memory use and speed.
"What if we reused objects instead of creating new ones each time? How would the time complexity change?"
Practice
heap memory in Java?Solution
Step 1: Understand what heap memory stores
Heap memory is used to store objects created dynamically using thenewkeyword in Java.Step 2: Differentiate from other memory areas
Primitive variables and method calls are stored on the stack, not heap. Bytecode is stored in method area, not heap.Final Answer:
It stores all objects created usingnewkeyword. -> Option CQuick Check:
Heap memory = objects fromnew[OK]
- Confusing stack with heap memory
- Thinking primitives are stored in heap
- Mixing method area with heap
Solution
Step 1: Identify object creation syntax
Objects in Java are created using thenewkeyword, which allocates memory on the heap.Step 2: Check each option
String s = new String("hello"); usesnew String("hello"), which creates a String object on the heap. Other options declare primitives stored on the stack.Final Answer:
String s = new String("hello"); -> Option AQuick Check:
Object creation uses new keyword [OK]
- Assuming primitives use heap
- Confusing string literals with new String()
- Ignoring that only new creates heap objects
class Test {
public static void main(String[] args) {
String a = new String("abc");
String b = a;
a = null;
System.out.println(b);
}
}Solution
Step 1: Understand object references and heap
Variableapoints to a String object "abc" in heap. Thenbis assigned the same reference.Step 2: Analyze effect of setting
Settingato nulla = nullremoves one reference, butbstill points to the object, so it remains accessible.Step 3: Print
Printingbboutputs the string "abc".Final Answer:
abc -> Option DQuick Check:
Reference b still points to "abc" [OK]
- Assuming object is deleted when one reference is null
- Confusing references with objects
- Expecting null output incorrectly
public class Demo {
public static void main(String[] args) {
int[] arr = new int[5];
arr = null;
System.out.println(arr.length);
}
}Solution
Step 1: Understand array creation and null assignment
The array is created on heap with size 5, thenarrreference is set to null.Step 2: Analyze printing
Sincearr.lengtharris null, accessingarr.lengthcauses a NullPointerException at runtime.Final Answer:
NullPointerException at runtime -> Option BQuick Check:
Accessing member on null reference throws exception [OK]
- Thinking null assignment causes compile error
- Expecting array length to print after null
- Confusing null with empty array
class Node {
int value;
Node next;
Node(int val) { value = val; }
}
public class Test {
public static void main(String[] args) {
Node n1 = new Node(1);
Node n2 = new Node(2);
n1.next = n2;
n2.next = n1;
n1 = null;
n2 = null;
// What happens to the Node objects in heap?
}
}What happens to the two
Node objects in heap after n1 and n2 are set to null?Solution
Step 1: Analyze object references after null assignments
Bothn1andn2references are set to null, so no external references point to these objects.Step 2: Understand garbage collection with cyclic references
Even though the two objects reference each other, Java's garbage collector detects unreachable cycles and frees them.Final Answer:
Both objects become unreachable and eligible for garbage collection. -> Option AQuick Check:
Unreachable objects, even cyclic, are collected [OK]
- Thinking cyclic references prevent garbage collection
- Assuming memory leak without external references
- Confusing references with reachability
Ready to prove it?
Pass the test and this pattern moves unknown
