Need to clarify the final StringBuffer object

In the general case, if a variable is declared final, we cannot override the value of this variable, but this does not work when we use a string buffer. Can someone tell me why?

The following code works !!!!!!

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

Output:

HelloWelcome

+4
source share
4 answers

From the Java Language Specification (highlighted by me):

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

So it's okay to control the state of the object pointed to by a

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

but simply cannot reassign a another object

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

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

There you always refer to the same object, and stringbuffer, unlike a string, is not immutable.

What you should get is that the value of your variable is a reference to a stringbuffer, not the actual contents of this object.

+4
source

You should read some Mutable and Immutable objects .

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

In mutable objects, you can change the state after it is built, for example

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

In an unchanged state, you cannot change the state of an object after it is built.

0
source

if the variable is declared final, we cannot override the value of this variable

Right. Once a final variable has been assigned, it cannot be reassigned. The compiler will not allow this.

but that doesn’t work when we use a string buffer.

Yes Yes.

The following code works !!!!!!

The code does not display the problem you are describing. It shows that the object whose reference is final can still be mutated. This is a completely different thing.

0
source

All Articles