Search code examples
javafinal

Can we change the value of a final variable of a mutable class?


Following is a code where I have tried to change the value of a final variable. First it prints "a" then "ab". So, if we can change the value of a final variable then what's the benefit of declaring a variable as final? what is use of final key word then? Please any one can help me with this?????

package test_new;
public class FinalVarValueChange {
    public static void main(String[] args){
       final StringBuffer s=new StringBuffer("a");
       System.out.println("s before appending  :"+s);
       s.append("b");
      System.out.println("s after appending  :"+s);     
   }
}

Solution

  • final does not enforce any degree of constancy of the object to which a reference is referring (it is not the same as const in C++).

    When you mark a variable as final, it means that you cannot assign a different object reference to that variable.

    For example, this code will not compile:

    final StringBuffer s=new StringBuffer("a");
    s = new StringBuffer("another a"); /*not possible to reassign to s*/
    

    It can be useful when using Runnables, Callables and locking idioms.