Search code examples
javafinalstringbuffer

Need clarification on final StringBuffer object


In general if a variable is declared final, we cant override the value of that variable but this doesn't hold good when we use string buffer. Can someone let me know why?

The below code works!!!!!!

  public static void main(String args[]) {
        final StringBuffer a=new StringBuffer("Hello");
        a.append("Welcome");
        System.out.println(a);
    }

Output:

HelloWelcome


Solution

  • From Java Language Specification (emphasis mine):

    Once a final variable has been assigned, it always contains the same value. If a final variable holds a reference to an object, then the state of the object may be changed by operations on the object, but the variable will always refer to the same object.

    So it is OK to manipulate state of object pointed by a

    a.append("Welcome"); //is OK
    

    but just can't reassign a with another object

    final StringBuffer a = new StringBuffer("Hello");
    a = new StringBuffer("World"); //this wont compile