Open In App

Why Java Strings are Immutable?

Last Updated : 20 Sep, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, strings are immutable, meaning their values cannot be changed once created. If you try to modify a string (e.g., using concat() or replace()), a new string object is created instead of altering the original one.

Reasons for Immutability

  • Strings are stored in a String Pool, allowing reuse of objects and reducing memory overhead.
  • Multiple threads can safely share the same string object without synchronization.
  • Immutable strings have a consistent hash code, making them reliable for use in collections like HashMap.
Java
public static void main(String[] args) {
        String s1 = "Hello";
        String s2 = s1;

        // Trying to modify s1
        s1 = s1.concat(" World");

        System.out.println("str1: " + s1); 
        System.out.println("str2: " + s2); 
    }

Output
knowledge base

Explanation: When we call s1.concat(" base"), it does not modify the original string "knowledge". It only creates a new string "knowledge base" and assigns it to s1. The original string remains unchanged.


Article Tags :

Explore