Case 1:

String str = "Good";
str = str + " Morning";

In the above code you create 3 String Objects.

  1. "Good" it goes into the String Pool.
  2. " Morning" it goes into the String Pool as well.
  3. "Good Morning" created by concatenating "Good" and " Morning". This guy goes on the Heap.

Note: Strings are always immutable. There is no, such thing as a mutable String. str is just a reference which eventually points to "Good Morning". You are actually, not working on 1 object. you have 3 distinct String Objects.


Case 2:

StringBuffer str = new StringBuffer("Good"); 
str.append(" Morning");

StringBuffer contains an array of characters. It is not same as a String. The above code adds characters to the existing array. Effectively, StringBuffer is mutable, its String representation isn't.

Answer from TheLostMind on Stack Overflow
🌐
Baeldung
baeldung.com › home › java › java string › create a “mutable” string in java
Create a “Mutable” String in Java | Baeldung
January 8, 2024 - Unlike other programming languages like C or C++, Strings are immutable in Java. This immutable nature of Strings also means that any modifications to a String create a new String in memory with the modified content and return the updated reference.
Discussions

Mutable or Immutable strings?
essentially, the string type is an alias to []byte Lol, I love the optimism. Unfortunately, your "strings are an array of characters/bytes/runes/whatever" assumption doesn't hold once you leave the world of ASCII. If you are using UTF-8 to encode your strings then replacing a u character with ü means you need to create a new copy of the string because the former is encoded as 0x55 while the latter is encoded as 0xC3 0xBC. If you decide to use UTF-16, you can say that string is an alias for u16[]. This mostly works, except there are more than 65536 unicode characters so you still need some form of variable-length encoding. Variable length encodings mean that "simple" operations like "get the 5th letter" require iterating through the entire string. Treating strings as arrays of unicode code points without any variable-length shenanigans (i.e. u32[]) gives you constant-time indexing again, but at the cost of 2-4x memory usage. Even then, treating strings as arrays of unicode code points isn't valid because a single "glyph" (single pictogram you might draw) may be composed of multiple code points. For example, the ü from earlier could have been written as combination of u and an umlaut accent. Individual programs can get away with being sloppy around handling unicode, but not a programming language. I'd take a note out of Go and Rust's book and treat strings as immutable, mostly opaque, UTF-8 bytes. TL;DR: Strings aren't arrays. Treating strings as arrays will teach your users bad habits. Modifying an existing string in place is not always possible. Welcome to the mess that is human language 🙂 More on reddit.com
🌐 r/ProgrammingLanguages
47
51
November 22, 2021
[Java] If strings are immutable why can their contents be changed?
It's not changing the contents of the string, it's creating a brand new string to which the string reference s now refers. The old string contents referred to by s are discarded and garbage collected. This would (if it were allowed in Java, which it isn't) change the contents of a string: String s = "a"; s[0] = 'z'; More on reddit.com
🌐 r/learnprogramming
10
32
April 30, 2016
Why String is immutable in Java
Can't help feeling that all the "reasons" given on this page are a lot of crock. They tend to boil down to "feature X wouldn't work with mutable strings" or "feature Y is made more complicated by mutable strings". If those arguments were valid, C's reliance on (completely mutable) char* variables would be folly. The real reason is simply that immutable data structures are, as a rule, easier to use and harder to misuse than their mutable counterparts. Strings being final and immutable in Java is just a design decision intended to make life simpler for developers. That, and maybe an expression of a desire for "primitive" string values -- real primitive types like int and float are immutable. More on reddit.com
🌐 r/java
23
4
January 20, 2012
What does 'Strings are immutable' mean?
A variable holds a reference to an object. You can see the reference with id(varaible). The string object that you have a reference to is immutable. When you reassign the variable to a new string, the reference is updated to point to a new string object, and the old string object is unchanged. Edit: Note that assignment assigns a reference. No matter whether the object being referred to is mutable, assignment to a variable updates the variable's reference. Mutating an object means changing the data held within an object in place - i.e. its reference does not change when mutated. More on reddit.com
🌐 r/learnprogramming
16
2
September 29, 2022
People also ask

What's the difference between mutable and immutable objects?
Mutable objects can be modified in place after creation; immutable objects cannot—any 'change' creates a new object instead.
🌐
interviewcake.com
interviewcake.com › interview cake › mutable vs immutable objects
Mutable vs. Immutable Objects Explained | Interview Cake
Which Python types are immutable?
Numbers (int, float), strings, tuples, frozensets, and booleans are immutable. Lists, dictionaries, and sets are mutable.
🌐
interviewcake.com
interviewcake.com › interview cake › mutable vs immutable objects
Mutable vs. Immutable Objects Explained | Interview Cake
Why does mutability matter in interviews?
It explains gotchas like shared references, mutable default arguments, and why only immutable (hashable) objects can be used as dictionary keys or set elements.
🌐
interviewcake.com
interviewcake.com › interview cake › mutable vs immutable objects
Mutable vs. Immutable Objects Explained | Interview Cake
🌐
Interview Cake
interviewcake.com › interview cake › mutable vs immutable objects
Mutable vs. Immutable Objects Explained | Interview Cake
June 17, 2026 - Strings can be mutable or immutable depending on the language. Strings are immutable in Java.
🌐
DEV Community
dev.to › arshisaxena26 › strings-understanding-mutability-and-immutability-4m4n
Strings: Understanding Mutability and Immutability - DEV Community
November 10, 2024 - These unused objects accumulate and contribute to increased garbage collection overhead. Java offers mutable alternatives like StringBuilder and StringBuffer to handle cases where strings are frequently modified.
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-string-is-immutable-what-exactly-is-the-meaning
Why Java Strings are Immutable? - GeeksforGeeks
June 15, 2026 - The original String "Hello" remains unchanged because Strings are immutable in Java.
Find elsewhere
🌐
Reddit
reddit.com › r/programminglanguages › mutable or immutable strings?
r/ProgrammingLanguages on Reddit: Mutable or Immutable strings?
November 22, 2021 -

What are the advantages of representing strings with an immutable data strucure?

A few good points i've read:

  • Easier to compare (compare by pointer)

  • Less expensive to copy

  • String pool cuts down the use of memory

Other than that, most other arguments are about immutable objects in general, ie. thread safety, optimizations, easier to reason, etc

That said, i'm considering to represent strings internally with a Mutable data structure, essentially, the string type is an alias to []byte (dynamic size byte array or byte slice), and as such is completely mutable. And here is why:

  • Fits better with the type system (specially with generics1), since all operations on slices can be done with strings

  • Less confusion on why you can mutate an item in a slice but not on a string

  • Less runtime complexity

Additionally, since function parameters are immutable by default in my language, we can pass slices by reference, not needing a copy. If you need to mutate an argument, however, i'm still deciding, either you need to explicitly pass a pointer to the value you want to mutate or you must specify that particular parameter as mutable.

1 - There are 5 (and only 5) typeclasses in my language: anything -> comparable -> orderable -> numerical -> integer. Each typeclass has associated operators. User defined types are automatically assigned to this typeclasses if they can be ordered, compared, etc. The language has an 'append' operator: a .. b appends b to the end of a, this operation is supported by both strings and slices. If strings are not slices, then i would need yet another typeclass to represent appendables. With strings being aliases, it's trivial to write generic algorythms that work in both slices and strings:

generic ReverseInPlace over T
    fn(list:&[]T) {
        var start = 0,
            end   = (@list).length;

        for start < end {
            val temp <- (@list)[start];
            (@list)[start] <- (@list)[end];
            (@list)[end] <- temp;

            start <- start + 1;
            end <- end - 1;
        }
    }

Edit: Thank you for all your input, after careful consideration, i decided to issue a compiler warning whenever string is indexed or mutated in place. That way the user will still be aware of string encodings but the type will fit well within the type system, without creating a special case. string is an alias to []byte but with training wheels, since the compiler knows this particular set of bytes is talking about the mess that is the human language. I'm sorry if that's not the outcome you expected, but in my view it's what best fits the language.

Top answer
1 of 12
79
essentially, the string type is an alias to []byte Lol, I love the optimism. Unfortunately, your "strings are an array of characters/bytes/runes/whatever" assumption doesn't hold once you leave the world of ASCII. If you are using UTF-8 to encode your strings then replacing a u character with ü means you need to create a new copy of the string because the former is encoded as 0x55 while the latter is encoded as 0xC3 0xBC. If you decide to use UTF-16, you can say that string is an alias for u16[]. This mostly works, except there are more than 65536 unicode characters so you still need some form of variable-length encoding. Variable length encodings mean that "simple" operations like "get the 5th letter" require iterating through the entire string. Treating strings as arrays of unicode code points without any variable-length shenanigans (i.e. u32[]) gives you constant-time indexing again, but at the cost of 2-4x memory usage. Even then, treating strings as arrays of unicode code points isn't valid because a single "glyph" (single pictogram you might draw) may be composed of multiple code points. For example, the ü from earlier could have been written as combination of u and an umlaut accent. Individual programs can get away with being sloppy around handling unicode, but not a programming language. I'd take a note out of Go and Rust's book and treat strings as immutable, mostly opaque, UTF-8 bytes. TL;DR: Strings aren't arrays. Treating strings as arrays will teach your users bad habits. Modifying an existing string in place is not always possible. Welcome to the mess that is human language 🙂
2 of 12
25
Seems like you’re conflating immutable strings with string pooling. I think immutable strings make sense, but deterministic string pooling is going to be a cache and synchronisation worst-case scenario. I can’t imagine going with that option on modern architectures. But then you don’t get benefits like pointer comparison.
🌐
Sololearn
sololearn.com › en › Discuss › 1005264 › is-string-mutable-or-immutable-in-javaand-why-it-is
Is string Mutable or Immutable in java?and Why it is?? | Sololearn: Learn to code for FREE!
January 15, 2018 - That all said, the variable that ... is meant by the somewhat confusing statement that strings are immutable. ... String is immutable in java........
🌐
MIT OpenCourseWare
ocw.mit.edu › ans7870 › 6 › 6.005 › s16 › classes › 09-immutability
Reading 9: Mutability & Immutability
String is immutable . Not only that, but this approach (unlike the previous one) gives the implementer the freedom to introduce a cache — a performance improvement. Since immutable types avoid so many pitfalls, let’s enumerate some commonly-used immutable types in the Java API: The primitive ...
🌐
Medium
medium.com › @priyasrivastava18official › java-interview-why-string-is-immutable-and-how-to-make-class-immutable-string-pools-concept-a4f93620d16d
Java Interview : Why String is immutable and how to make class immutable , String pools concept | by Priya Srivastava | Medium
October 7, 2024 - Since String is immutable, its hash code is cached at the time of creation, and it doesn’t need to be calculated again. This makes it a great candidate for keys in a Map, and its processing is faster than that of other HashMap key objects.
🌐
Medium
medium.com › @rohitpatil3898 › strings-immutability-in-java-bd59744b72cd
Strings & Immutability in JAVA. Strings are the sequence of characters… | by Rohit Raghunath Patil | Medium
October 12, 2024 - String is an Immutable class in Java. Once a String object is created, it cannot be changed. When we assign the String to a new value, a new object is created. String literal is zero or more characters enclosed in double quotes.
🌐
EDUCBA
educba.com › home › software development › software development tutorials › java tutorial › mutable string in java
Mutable String in Java | 2 Main Constructors of Mutable String in Java
March 23, 2023 - Therefore mutable strings are those strings whose content can be changed without creating a new object. StringBuffer and StringBuilder are mutable versions of String in java, whereas the java String class is immutable.
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
Upgrad
upgrad.com › home › tutorials › software & tech › why string is immutable in java?
Why String Is Immutable in Java: Unraveling the Immutable Nature of Java Strings
February 4, 2025 - Because strings are immutable, multiple references can safely share the same object, which saves memory and reduces object creation overhead in applications. Other objects can be mutable because they are often designed to change state.
🌐
JavaGoal
javagoal.com › home › what is a mutable string
mutable string in java and How does mutable string work - JavaGoal
November 19, 2022 - In a mutable string, we can change the value of the string in the same object. To create a mutable string in java, Java has two classes StringBuffer and StringBuilder where the String class is used for the immutable string.
🌐
Scaler
scaler.com › home › topics › why string is immutable in java?
Why String is Immutable in Java? - Scaler Topics
March 28, 2024 - Java String class provides a lot of methods to perform operations on strings. A string is an immutable object which means we cannot change them after creating the objects. Whenever we change any string, a new instance is created. In this article, we will explore Why Strings are immutable in ...
🌐
YouTube
youtube.com › watch
#35 Mutable vs Immutable String in Java - YouTube
Check out our courses:Mastering Agentic AI with Java : https://go.telusko.com/agentic-aiCoupon: TELUSKO10 (10% Discount)DevOps Bootcamp: https://go.telusko...
Published   January 18, 2023