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
Understanding Java String Immutability and Assignment

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.

Javaprogrammingstringfundamentalsimmutability
Java Captain
Written by

Java Captain

Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.

0 followers
Reader feedback

How this landed with the community

login 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.