4

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

Learner
  • 2,303
  • 9
  • 46
  • 81

4 Answers4

9

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
Pshemo
  • 122,468
  • 25
  • 185
  • 269
4

What you can't do with a final variable is change it to reference another object (or primitive value) or null.

There, you always reference the same object and a stringbuffer, contrary to a string, isn't immutable.

What you must get is that the value of your variable is a reference to the stringbuffer, not the actual content of that object.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
0

You should do some read on Mutable and Immutable objects.

Example of immutable classes: String, Integer, Long Example of mutable classes: StringBuffer, Date

In mutable objects you can change state after its construction, e.g.

final StringBuffer a=new StringBuffer("Hello");
a.append("Welcome");

In immutable you cannot change state of the object after its construction.

user1697575
  • 2,830
  • 1
  • 24
  • 37
0

if a variable is declared final, we cant override the value of that variable

Correct. Once a final variable has been assigned it cannot be reassigned. The compiler will not permit it.

but this doesn't hold good when we use string buffer.

Yes it does.

The below code works!!!!!!

The code does not exhibit the problem you describe. It shows that an object whose reference is final can still be mutated. That's a completely different thing.

user207421
  • 305,947
  • 44
  • 307
  • 483