What if changing a word could break your whole program without you knowing?
Why String immutability in Java? - Purpose & Use Cases
Imagine you have a list of names written on sticky notes. If you want to change a name, you have to erase and rewrite it on the same note. But what if someone else is reading that note at the same time? They might see the name half-erased and get confused.
Changing strings directly can cause confusion and mistakes, especially when many parts of a program use the same string. If one part changes it, others might see unexpected results. This makes programs buggy and hard to fix.
String immutability means once a string is created, it cannot be changed. Instead, if you want a different string, you create a new one. This keeps all parts of the program safe and consistent, like giving each reader their own copy of the note.
String name = "Alice"; name = name.replace('A', 'E'); // reassigns name to a new string
String name = "Alice"; String newName = name.replace('A', 'E'); // creates new string
This makes programs safer and easier to understand because strings never change unexpectedly.
When multiple users access the same text in a chat app, string immutability ensures each user sees the correct message without accidental changes.
Strings cannot be changed once created.
Changing a string creates a new one instead.
This prevents bugs and keeps data safe.
