Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 362
Learner Avatar asked Dec 11 '22 16:12

Learner


1 Answers

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
like image 53
Pshemo Avatar answered Jan 02 '23 23:01

Pshemo