Video in progress
What does it give you in practice that String is immutable?
A String, once created, never changes. Because of that, it can be shared safely between threads, reused in the String pool, have its hash cached, and be used freely as a HashMap key.
📖 Answer
Every method that "changes" it actually returns a new object:
String s = "salom";
s.toUpperCase(); // the result was thrown away
System.out.println(s); // salom
s = s.toUpperCase(); // now s points to a new object
What do we gain? If you validate a file path or a URL and then use it, nobody can change it in between. Threads can share it without synchronization. Identical literals sit in the pool as a single object, which saves memory. And hashCode() is computed once and stored, which is exactly what you want for a HashMap key.
The price: if you build text with += in a loop, a new object appears at every step. That's what StringBuilder is for.
Sign up to mark studied questions and save your progress.