Why are Strings Immutable in Java

In Java, strings are immutable means their values cannot be changed once they are created. This feature enhances performance, security, and thread safety. In this article, we will explain why strings are immutable in Java and how this benefits Java applications.

What Does Immutable Mean?

An immutable object is an object whose state cannot be modified after it is created. In Java, this concept applies to strings, which means that once a string object is created, its content cannot be changed. If we try to change a string, a new string object is created instead.

How are Strings Immutable in Java?

Strings in Java that are specified as immutable, as the content shared storage in a single pool to minimize creating a copy of the same value. String class and all wrapper classes in Java that include Boolean, Character, Byte, Short, Integer, Long, Float, and Double are immutable. A user is free to create immutable classes of their own.

Let’s understand this with an example:

public class Main {

    public static void main(String[] args) {

        String s1 = "knowledge";
        String s2 = s1;            // s2 points to the same "knowledge"
        s1 = s1.concat(" base");   // creates a new String "knowledge base"

        System.out.println(s1);   
    }
}
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.

Why Are Java Strings Immutable?

  1. String Pool: Java stores string literals in a pool to save memory. Immutability ensures one reference does not change the value for others pointing to the same string.
  2. Security: Strings are used for sensitive data like usernames and passwords. Immutability prevents attackers from altering the values.
  3. Thread Safety: Since string values cannot be changed, they are automatically thread-safe, means multiple threads can safely use the same string.
  4. Efficiency: The JVM reuses strings in the String Pool by improving memory usage and performance.

Example to Demonstrate String Immutability

The below programs demonstrate the immutability of Java strings.

// Java Program to demonstrate why Java Strings are immutable

import java.io.*;
class GFG {
    public static void main(String[] args) {
        String s1 = "java";
        // creates a new String "java rules", but does not change s1
        s1.concat(" rules");
        // s1 still refers to "java"
        System.out.println("s1 refers to " + s1);
    }
}
Output
s1 refers to java

Explanation: In the above example, even though we call concat() to append " rules", the original string s1 still refers to "java". The new string "java rules" is created, but it is not assigned to any variable, so it is lost.

Java Strings Immutable – FAQs

What is String Immutability in Java?

String immutability means that once a string object is created, its value cannot be changed. Any modification results in the creation of a new string.

Why are Strings Immutable in Java?

Strings are immutable for security, performance, and thread safety reasons. It prevents unwanted changes and helps optimize memory usage.

Can We Modify a String in Java?

No, we cannot modify a string directly. Any modification creates a new string object.

What Happens if We try to Modify a String in Java?

Modifying a string results in a new string being created. The original string remains unchanged.

How does String Immutability Help with Memory Efficiency?

Immutability allows Java to reuse string objects from the String Pool, saving memory and improving performance by avoiding duplicate string objects.


Post a Comment

Previous Post Next Post