๐Ÿงต

Java String Handling Deep Dive

Jun 22, 2024

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

  1. String s = new String("durga");
  2. String s = "durga";

Key Differences

  • New Operator (new String("durga")):

    • Two objects created: one in heap, one in the String Constant Pool (SCP).
    • s points to the object in the heap.
  • Literal ("durga"):

    • One object created in SCP.
    • s points to the object in SCP.

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
    1. "durga"
    2. "durga software"
    3. "durga software solutions"
  • SCP Objects Created:
    1. "durga"
    2. "software"
    3. "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)