Sobes.tech
Junior — Middle

Explain the concept of strings that cannot be changed after their creation.

sobes.tech AI

Answer from AI

In Java, strings (objects of the String class) are immutable. This means that once a string object is created, its contents cannot be changed.

If you perform operations that seem to modify a string (for example, concatenation), a new String object with the new content is actually created, and the old one remains unchanged.

This ensures safety when working with strings in a multithreaded environment and allows strings to be used as keys in collections without the risk of modification.

Example:

String s = "Hello";
String t = s + " World"; // a new string object is created
// s remains "Hello"
// t contains "Hello World"