Java Strings: Immutability, String Constant Pool & Core Methods

In Java, a String is an object that encapsulates an immutable sequence of characters. Unlike C/C++ where strings are simple null-terminated character arrays, Java treats strings as first-class objects defined in the java.lang.String class.

Java String Constant Pool SCP Memory Architecture

Figure 7: Memory Model of String Literals inside the SCP vs new String() Heap Objects.

1. String Literals vs. new String()

  • String Literal (String s = "Java";): Stored in the String Constant Pool (SCP). If "Java" already exists in the pool, no new object is created; the existing reference address is shared.
  • Using new Keyword (String s = new String("Java");): Forces the JVM to allocate a brand-new object in the general Heap memory, outside the SCP pool, even if the literal already exists.

The == Operator vs. .equals() Method

public class StringComparisonDemo {
    public static void main(String[] args) {
        String s1 = "Veewom";
        String s2 = "Veewom";
        String s3 = new String("Veewom");

        // 1. Reference comparison (==):
        System.out.println("s1 == s2: " + (s1 == s2)); // true (Both point to same SCP address!)
        System.out.println("s1 == s3: " + (s1 == s3)); // false (s3 points to separate Heap address!)

        // 2. Content comparison (.equals()):
        System.out.println("s1.equals(s3): " + s1.equals(s3)); // true (Identical characters!)

        // 3. The .intern() method:
        String s4 = s3.intern(); // Fetches reference from SCP pool
        System.out.println("s1 == s4: " + (s1 == s4)); // true!
    }
}

Essential Java String Methods

Method Description Example (s = "Hello World")
length()Returns character counts.length() → 11
charAt(index)Returns char at specified indexs.charAt(0) → 'H'
substring(begin, end)Extracts substring (end exclusive)s.substring(0, 5) → "Hello"
contains(seq)Checks if substring existss.contains("World") → true
toUpperCase()Converts to all uppercases.toUpperCase() → "HELLO WORLD"
trim() / strip()Removes leading/trailing whitespace" Hi ".strip() → "Hi"
split(regex)Splits string into array by delimiters.split(" ") → ["Hello", "World"]

University Exam Corner (BCA / B.Sc CS)

Frequent Exam Question: "How many objects are created in memory by: String s = new String("Java");?"

Answer: Two objects! (Assuming "Java" is not already in the pool):
1. One object is created in the String Constant Pool (SCP) for the literal parameter "Java".
2. A second distinct object is created in the general Heap memory by the new operator.
The variable s points to the object in general Heap memory.

Next Step

Because String is immutable, repeated concatenation in loops creates massive garbage. Let us explore mutable StringBuilder and StringBuffer. Proceed to: StringBuilder vs StringBuffer →

Frequently Asked Questions (FAQ)

Q1. Why are String objects immutable in Java?
Strings are immutable for four critical architectural reasons: 1. Security (prevents corruption of network sockets, file paths, and database URLs), 2. Thread-Safety (immutable objects can be shared across threads with zero synchronization overhead), 3. Caching & Memory Efficiency (String Constant Pool reuse), and 4. HashCode Caching (ideal keys in HashMaps).
Q2. What is the String Constant Pool (SCP) in Java?
The String Constant Pool is a specialized memory cache located inside the Java Heap. When a string literal is created (e.g. String s = 'Java'), the JVM checks the SCP: if it already exists, the existing reference is reused, saving significant memory.
Q3. What is the difference between == and .equals() when comparing Strings?
The == operator compares reference memory addresses (verifies if both variables point to the exact same Heap object). The .equals() method compares the actual textual character contents sequence by sequence.

Explore Related Java Tutorials

Accelerate your Java mastery by studying these tightly connected core tutorials:

StringBuilder & StringBuffer →

Mutable string alternatives.

Java Regular Expressions →

Pattern matching with strings.

Wrapper Classes →

Converting strings to primitives.

JVM Memory Management →

Heap allocation details.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!