Course contentsShow
← Computer Science
Lesson 262 of 2,8726. Arrays and Basic CollectionsFree lesson

String Immutability

Understanding that strings are typically immutable and how modifications create new string objects rather than changing existing ones.

String Immutability

What you'll learn: You'll understand why strings don't change in place and what happens when you "modify" them.

The Core Idea

In most programming languages, strings are immutable — once created, they cannot be changed. When you appear to modify a string (like changing a character or adding text), you're not actually altering the original string. Instead, the language creates a brand new string object with the desired changes, leaving the original untouched.

Think of strings like writing on a sealed document. You can't erase or change what's already written. If you need different text, you must create an entirely new document with the new content.

Why It Matters

Remember that strings are arrays of characters? Unlike regular arrays where you might change arr[0] = 'X', you typically cannot do myString[0] = 'X'. The string remains frozen.

For example, if you have a string "hello" and want to make it "Hello" (capital H), you can't just replace the first character. The language creates a completely new string "Hello" in memory, and your variable now points to this new string. The original "hello" stays unchanged (until it's cleaned up if nothing else references it).

Performance Implications

Creating new strings on every modification seems wasteful, but immutability brings benefits: strings can be safely shared between different parts of your program without fear of unexpected changes. However, if you need to build strings through many small changes (like in a loop), repeated creation of new strings can be slow — that's why languages offer specialized tools for efficient string building (which you'll learn later).

Key Takeaway: Strings are immutable — modifications create new string objects rather than changing the originals, ensuring safety but requiring awareness of performance trade-offs.