You interchange immutability with what final
modifier can achieve.
If you declare a variable as final, it means the reference cannot point to another instance than initialized:
final String string = "A";
string = "B"; // won't compile
String anotherString = "A"
anotherString = "B"; // this is okey
The point of immutability is that the inner fields of the instance doesn't change. The methods of String
returns a new String
from the original one while it remains unchanged:
String string = "A";
string.toLowerCase(); // will be still "A"
String anotherString = "A";
String newString = anotherString.toLowerCase();
// anotherString is "A"
// newString is "a"
Note the use of immutable object doesn't require final
modifier, yet it's used to achieve immutability itself in the object which is designed as immutable. This class is immutable since bar
is instaninated once and never changed:
public class Foo {
private final int bar;
public Foo(int bar) {
this.bar = bar;
}
}