Junior — Middle
Could you explain what objects that cannot be changed after creation are?
sobes.tech AI
Answer from AI
Objects that cannot be changed after creation are called immutable. In Java, examples of such objects are strings (String) and wrappers over primitives (e.g., Integer, Double).
Immutability means that once an object is created, its state cannot be changed. This is useful for:
- Security in multithreaded applications (no synchronization issues).
- Simplifying caching and reuse of objects.
- Predictability of code behavior.
Example:
String s = "hello";
// s cannot be changed, only a new string can be created
String t = s.toUpperCase(); // a new object "HELLO" is created
Thus, immutable objects ensure data stability and security.