I mean, why do defacto immutable objects exists? Why do we not just use the final static modifiers? What is so important about String that Java makes it immutable?

- 94,330
- 19
- 181
- 276

- 1,792
- 22
- 34
-
1immutable classes are thread safe. also check [this](http://stackoverflow.com/questions/5652652/java-advantages-of-of-immutable-objects-in-examples) – SomeJavaGuy Oct 15 '15 at 14:57
2 Answers
Making a variable final makes that reference unchangeable. But the object that the reference points to can still change, so if I define:
final List<String> list = new ArrayList<String>();
I can't swap the list out for another list, but I can still modify the contents of the list:
list.add("asdf");
But an immutable object cannot be changed once it is constructed.
(Using static only means the field is defined on the class, not on the instance. It's used for defining constant values (moreso before enums were added) but only because only one value is needed for the class. The static keyword's not directly relevant for immutability.)
Immutable objects are threadsafe and concerns about memory visibility, lost updates, etc. are not applicable, because the object's state is safely published upon construction.
They are easy to reason about because there are no state changes. For things with value-based equality, immutability is a better match for the concept being described. For Strings and numbers, that are unchanging abstractions, immutability is especially appropriate.
If you have a mutable object where a mutable field participates in its equals and hashCode implementation, then you can have a situation where you put it in a collection, then mutate the field, breaking how the collection works. It's better to avoid that kind of thing up front.
Also immutable objects are safer to share, see Java Concurrency in Practice, 3.4:
Immutable objects are also safer. Passing a mutable object to untrusted code, or otherwise publishing it where untrusted code could find it, is dangerous -- the untrusted code might modify its state, or worse, retain a reference to it and modify its state later from another thread. On the other hand, immutable objects cannot be subverted in this manner by malicious or buggy code, so they are safe to share and publish freely without the need to make defensive copies.

- 94,330
- 19
- 181
- 276
Final Static Variables -> one instance for the class. You can not change. Supports multi-threading. Immutable Objects -> Each class will have its instance variable. You can change. Supports multi-threading.

- 1