Last Updated : 11 Jul, 2025
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 are going to learn why strings are immutable in Java and how this benefits Java applications.
What Does Immutable Mean?When we say something is immutable, it means that once it is created, it cannot be changed. 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, Java does not modify the original one, it creates a new string object instead.
How are Strings Immutable in Java?Java strings are immutable to make sure memory is used efficiently. Strings in Java that are specified as immutable as the content is 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.
When we use methods like concat() or replace(), they don’t alter the original string but create a new one with the new content. This helps avoid bugs that might arise from modifying shared data across different parts of the program.
Let's understand this with an example:
Java
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);
}
}
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?The below program demonstrate the immutability of Java strings, where we try to modify a string using concat():
Java
// 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);
}
}
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.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4