← Back to list

Why Strings Are Immutable in Java (And Why It Matters)

What Does Immutable Mean?

Kothapalli Gayathri · 2026-03-30 17:06 · 0 claps · 1.1 min read
#java #string-concept #programming-concepts #coding-basics
Open on Medium ↗
Wiki topics: GEN · Genomics & Sequencing 💻 · Programming

Why Strings Are Immutable in Java (And Why It Matters)

What Does Immutable Mean?

In Java, immutable means:

Once a String object is created, its value cannot be changed.

If you try to change it, Java creates a new String object instead.

Example:

String str = "Hello";
str = str + " World";  // trying to change original string

What happens here?

  1. str initially points to "Hello" in memory.
  2. str + " World" does not modify the original string.
  3. Java creates a new String object "Hello World" and str now points to it.
  4. "Hello" still exists in memory (interned in String pool).

Memory Explanation

Java uses String Pool:

  • Strings literals are stored in a special memory area called the String Pool.
  • Immutability ensures that multiple variables can point to the same String object safely.
String a = "Java";
String b = "Java";

System.out.println(a == b);  // true, both point to same object

If strings were mutable, changing one variable would accidentally affect the other.

Why Strings Are Immutable — Key Reasons

Security

  • Strings are used in sensitive things (like URLs, passwords, file paths).
  • Immutability prevents accidental or malicious changes.

Thread Safety

  • Multiple threads can use the same String safely.

Hashcode Consistency

  • Strings are used as keys in HashMaps. If they were mutable, the hashcode could change, breaking maps.

Efficiency (String Pool)

  • Reusing same immutable objects saves memory.

Example Showing Safety:

String a = "Java";
String b = a;

a = a + " Programming";

System.out.println(a);  // Java Programming
System.out.println(b);  // Java
  • b is not affected because Strings are immutable.
  • If Strings were mutable, b would also have changed.

Final Thought

Immutability may seem restrictive at first, but it makes Java safer, faster, and reliable.


메타데이터
post_id
1efbb603d779
slug
why-strings-are-immutable-in-java-and-why-it-matters-1efbb603d779
url
https://medium.com/@kothapalli-gayathri/why-strings-are-immutable-in-java-and-why-it-matters-1efbb603d779
canonical_url
https://medium.com/@kothapalli-gayathri/why-strings-are-immutable-in-java-and-why-it-matters-1efbb603d779
author_url
https://medium.com/@kothapalli-gayathri
status
ok
fetched_at
2026-07-28 03:40:04