0
0
Javaprogramming~15 mins

String immutability in Java

Choose your learning style8 modes available
menu_bookIntroduction

Strings in Java cannot be changed once created. This helps keep data safe and programs reliable.

When you want to store text that should not change, like a username or ID.
When sharing text data between different parts of a program without risk of accidental changes.
When using strings as keys in collections like HashMap to avoid unexpected behavior.
When you want to improve performance by reusing string objects safely.
When working with multithreaded programs to prevent data conflicts.
regular_expressionSyntax
Java
String text = "Hello";
// text cannot be changed after this

Strings are objects but behave like fixed text.

Any change creates a new String object instead of modifying the original.

emoji_objectsExamples
line_end_arrow_notchThis looks like changing the string, but actually a new string is created and greeting points to it.
Java
String greeting = "Hi";
greeting = greeting + " there!";
System.out.println(greeting);
line_end_arrow_notchAssigning one string to another copies the reference, not the string itself.
Java
String name = "Alice";
String copy = name;
// Both name and copy point to the same string object "Alice"
code_blocksSample Program

This program shows that the original string stays the same after trying to replace a character. A new string is created instead.

Java
public class Main {
    public static void main(String[] args) {
        String original = "Cat";
        String changed = original.replace('C', 'B');
        System.out.println("Original: " + original);
        System.out.println("Changed: " + changed);
    }
}
OutputSuccess
emoji_objectsImportant Notes
line_end_arrow_notch

Because strings are immutable, methods like replace() return new strings.

line_end_arrow_notch

Use StringBuilder if you need to change text many times for better performance.

list_alt_checkSummary

Strings cannot be changed after creation.

Changing a string creates a new string object.

Immutability helps keep programs safe and predictable.