Sitemap
Anuraag Ojha

Anuraag Ojha

🚀 Software professional with 10+ years of experience in software development and DevOps, driving innovation and efficiency.

Understanding Java String Immutability

3 min readMar 12, 2025

--

In Java, Strings are immutable, which means that once a String object is created, its value cannot be changed. This characteristic is a fundamental feature of Java Strings, providing both security and performance benefits in various applications.

What Does String Immutability Mean?

When we say that a String is immutable in Java, it means that the state of the String object cannot be altered after it is created. If any operation is performed on a String object that seems to modify its content, a new String object is created instead.

Get Anuraag Ojha’s stories in your inbox

Join Medium for free to get updates from this writer.

Let’s explore this concept with a detailed explanation and example.

Why Are Strings Immutable?

  1. Security: Since Strings are widely used in applications (such as database connections, passwords, etc.), their immutability ensures that their value cannot be changed unexpectedly, which would otherwise create vulnerabilities.
  2. Hashcode Caching: Strings are often used as keys in hash-based collections like HashMap. The immutability of Strings ensures that their hashcode is computed once and doesn't change, thus maintaining consistency when used as a key.
  3. Performance (String Pool): In Java, there is something called a String Pool (or String Literal Pool). If you create a string with the same value more than once, Java uses the same object from the pool instead of creating a new one. This improves memory usage and performance.

String Immutability in Action

Here is an example demonstrating the immutability of Strings:

public class StringImmutabilityExample {
public static void main(String[] args) {
// Create a String object
String str = "Hello";
        // Try modifying the string (which actually creates a new object)
str = str.concat(" World");
// Output the modified string and the original
System.out.println("Modified String: " + str); // Outputs: Hello World
System.out.println("Original String: " + "Hello"); // Outputs: Hello
}
}

Explanation of the Code:

  1. Original String: The string "Hello" is created.
  2. String Modification: The method concat() is called on the string. Since String is immutable, instead of modifying the original string, the concat() method creates a new String object with the value "Hello World" and assigns it to the variable str.
  3. Printing the Result: When we print the modified string (str), it outputs "Hello World", while the original string ("Hello") remains unchanged.

Key Points:

  • Strings are stored in a special memory area called the String Pool.
  • Operations like concat(), toLowerCase(), replace(), etc., don't modify the original string but create new strings with the required transformation.
  • StringBuilder or StringBuffer should be used if you need to perform a lot of modifications to a string since they are mutable.

Performance Implications:

Since every modification to a string creates a new object, excessive concatenation can lead to memory overhead. For example, consider the following:

public class StringConcatenationExample {
public static void main(String[] args) {
String result = "";
for (int i = 0; i < 1000; i++) {
result += "Java"; // Creates a new string object every time
}
System.out.println(result);
}
}

The above code creates 1000 new String objects as each += operation creates a new string. To optimize this, use StringBuilder:

public class StringBuilderExample {
public static void main(String[] args) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < 1000; i++) {
result.append("Java");
}
System.out.println(result.toString());
}
}

Here, StringBuilder optimizes string concatenation by modifying the same internal buffer rather than creating new objects each time, resulting in improved performance.

Conclusion:

  • Immutability: Strings in Java are immutable, meaning their values cannot be changed once created.
  • Security and Performance: This immutability provides security (by preventing unintentional changes) and performance optimizations (like string pooling and caching of hashcodes).
  • Efficient String Manipulation: Use StringBuilder or StringBuffer for frequent string manipulations to avoid unnecessary object creation and improve performance.

By understanding String immutability, you can write more efficient, secure, and reliable Java applications.

--

--

Anuraag Ojha

Written by Anuraag Ojha

🚀 Software professional with 10+ years of experience in software development and DevOps, driving innovation and efficiency.