How Does Java Strings are Immutable - Here's What That Actually Means Work?

Java strings are immutable, which means once you make one, you can’t really change it, like a sealed lunch box.

Imagine you have a sealed lunch box labeled "pizza". No matter how hard you try, you can't just reach in and switch the pizza for a sandwich. If you want a sandwich, you need to get a new lunch box and label it "sandwich".

Like a Permanent Tag

When you create a string in Java, it's like writing a permanent tag on your lunch box. You can’t erase or rewrite that tag, but you can make a brand new lunch box with the new name.

So if you have String food = "pizza"; and then do food = "sandwich";, you're not changing the original lunch box. You're just getting a new one labeled "sandwich".

No More Magic, Just Real Life

This might sound simple, and it is! It’s like having to get a new tag every time you want to change your lunch box's contents. No need for magic, just a little extra work if you're changing things often.

Take the quiz →

Ask a question

See also

Loading…

Discussion

Recent activity

Categories: Science