If you are a C# developer, like myself, and start learning Java (for whatever reason), there will be a lot of ‘what-the-heck’ question. One of mine was the
final keyword in Java.
final means just that, final. You can only initialize it once and it can’t be changed anymore for its entire life. I think in C#, we call it
Immutability with Final
final is often used to achieve immutability in Java. However, it won’t make the objects themselves immutable. In other words,
final only gives you the sense of immutability, but it doesn’t modify the object to be truly immutable.
Primitive types such as int, long or short can be reassigned after being defined.
final will prevent this.
int i = 42; //int is of primitive type
i = 43; // OK
final int j = 42;
j = 43; // does not compile. j is final so can't be reassigned
Reference types cannot be made immutable just by using the
final only prevents reassignment.
final MyObject m = new MyObject(); //m is of reference type
m.data = 100; // OK. We can change state of object m (m is mutable and final doesn't change this fact)
m = new MyObject(); // does not compile. m is final so can't be reassigned