Skip to content
Understanding Java String Immutability and Assignment
Fundamentals 2 min read

Understanding Java String Immutability and Assignment

This article explains how Java strings are defined, how assigning one string variable to another copies the reference, how concatenation creates a new immutable string object, and why mutable alternatives like StringBuilder should be used to avoid excessive garbage collection.

Java Captain
Java Captain
Java Captain

Define a String

String s = "abcd";

The variable s stores a reference to a String object; the arrow in the accompanying diagram indicates that the reference is stored.

Assign a Variable to Another Variable

String s2 = s;

The variable s2 holds the same reference value as s, representing the same object.

String Concatenation

s = s.concat("ef");

After concatenation, s now references a newly created String object.

Summary

Once a String object is created in heap memory, it cannot be modified. All methods of the String class return new objects rather than altering the original string.

If a mutable string is needed, use StringBuffer or StringBuilder; otherwise, many temporary objects will be created, leading to unnecessary garbage‑collection overhead.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaprogrammingStringfundamentalsimmutability
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.