Lecture Notes on Immutability, Mutability, and String Handling in Java
Overview
- Previous Topics Covered: Immutability, mutability,
equals method, difference between String and StringBuffer.
- Current Focus: Deep dive into string handling
String Object Creation
Comparison of Two Methods
String s = new String("durga");
String s = "durga";
Key Differences
Detailed Explanation
- Heap Area:
- Objects created here are eligible for garbage collection.
- String Constant Pool (SCP):
- Contains string literals, reused to save memory.
- Objects not eligible for garbage collection as JVM maintains an implicit reference.
Historical Notes on SCP
- Up to Java 1.6:
- SCP was part of the Method Area or Permanent Generation (PermGen).
- Post Java 1.7:
- SCP moved to the heap area for efficient memory utilization.
- SCP became expandable as part of the heap.
Example Scenarios
Creating Strings Using new and Literals
String s1 = new String("durga");
String s2 = new String("durga");
String s3 = "durga";
String s4 = "durga";
- s1 and s2:
- Two heap objects, one SCP object reused.
- s3 and s4:
- No new objects in heap; SCP object reused.
Runtime Modifications
String s = new String("durga");
String modified = s.concat("software");
- s.concat("software"):
- Creates a new object in the heap.
- Original object in SCP is not changed.
Complex Example
String s = new String("durga");
s = s.concat("software");
s = s.concat("solutions");
- Heap Objects Created: 3
- "durga"
- "durga software"
- "durga software solutions"
- SCP Objects Created:
- "durga"
- "software"
- "solutions"
Summary
- New Operator: Always creates a new object in the heap.
- Literal: May reuse existing objects in SCP.
- Heap vs SCP:
- Heap: Runtime operation objects, eligible for garbage collection.
- SCP: Reused string literals, not eligible for garbage collection.
[Music] (Transitional marker indicating the end of lecture)