Strings are one of the most commonly used objects in Java. A String is immutable, which means that once a String object is created, its value cannot be changed.
Strings are stored in a String Pool, allowing reuse of objects and reducing memory overhead.
Multiple threads can safely share the same string object without synchronization.
Output
Hello
Explanation: In the above example, the concat() method does not modify the original String object. When str.concat(" World") is executed:
A new String object "Hello World" is created.
The original String "Hello" remains unchanged.
Since the new object is not assigned to any variable, it is discarded.
The original String "Hello" remains unchanged because Strings are immutable in Java. The concat() method creates a new String object "Hello World", but since it is not assigned to any variable, the output remains "Hello".
How to Modify a String?
Since Strings cannot be modified directly, you must store the result in a new reference.
Output
Hello World
Explanation: Here, the newly created String object is assigned back to str, so the reference now points to the updated String.
Why Are Strings Immutable
Security: Prevents sensitive data such as passwords, file paths, and URLs from being modified after creation.
String Pool Optimization: Allows multiple references to safely share the same string object, saving memory.
Thread Safety: Multiple threads can access the same string object without synchronization issues.
HashCode Caching: The hashcode remains constant, improving the performance of collections like HashMap.
Better Memory Management: Immutable strings can be reused, reducing unnecessary object creation.