Sitemap

Member-only story

Why is String Immutable in Java?

Learn why String is immutable in Java, how it works internally, and the benefits like security, caching, and thread-safety. Includes real-world examples.

2 min read
·
Mar 25, 2025

--

What Does “Immutable” Mean?

Immutable means: once a String object is created, it cannot be changed.

Even if you try to modify it, a new String object is created, and the original stays unchanged.

📌 Example:

String name = "Ramesh";
name.concat(" Fadatare");
System.out.println(name); // Output: Ramesh (Not "Ramesh Fadatare")

Even after calling .concat(), the original name didn’t change.

🔍 Why Was String Made Immutable?

Let’s explore the key reasons why Java designers made String immutable:

1️⃣ Security

Many sensitive operations like:

  • File path access
  • Class loading (Class.forName("com.example.MyClass"))
  • Network URL handling use String.

If String were mutable, someone could change the value after authentication, leading to serious security breaches.

2️⃣ String Pooling (Memory Efficiency)

--

--

No responses yet

Morty Proxy This is a proxified and sanitized view of the page, visit original site.