I was recently asked this quesion. But was not able to explain concisely what exactly sets both these concepts apart.
For example
Final and Immutable:<
Immutable:
when you change the String, create new String object ('abcdef') and change the reference from 'abce' to 'abcdef'.But you can not remove 'abcd'. Only change the reference. That is immutable.
final:
Actually final is a keyword.When you add it to variable, you can not change the reference.
When you have a field declared as final
, the reference will not change. It will always point at the same Object.
if the Object is not immutable
, the methods on it can be used to change the Object itself - it is the same Object, but its properties have been changed.
When you use keyword "final", that means that you cannot change the reference of the object that the variable points to. So, in this case variable "name" cannot be made to point to another string object. However, please note that we can change the contents of the object since we are using a final reference. Also Strings in java are inherently immutable. i.e. you cannot change its contents. So, in your case, final will make a final reference to a string object. and since you can't change the variable to point to another string object, code fails.
See the code below to understand working of final variable.
public class test {
public static void main(String[] args) {
final A aObject = new A();
System.out.println("Old value :" + aObject.a);
aObject.a = 2;
System.out.println("New value :" + aObject.a);
}}
class A {
public int a = 1;}