Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How the final keyword work with StringBuilder?

Tags:

java

Why below code is not throwing any exception while final used?
final StingBuilder sb=new StingBuilder("Satya");
sb.append("Pune");

like image 648
Satya Avatar asked Mar 10 '26 15:03

Satya


2 Answers

final only says the variable cannot be reassigned. but the attributes of the variable can still be changed

final means in this case: that the reference to the object is final (it can only be assigned once), not the object itself.

The object itself can still be modified.

like image 109
Abdelhak Avatar answered Mar 12 '26 05:03

Abdelhak


final means shallow immutability.

Java only has primitive and reference variables and in this case StringBuilder sb is a reference to a StringBuilder and that reference is immutable. ie. you can't do sb = null; later.

However, the object referenced is not made also immutable and you can still call methods which alter the StringBuilder via this reference.

like image 38
Peter Lawrey Avatar answered Mar 12 '26 04:03

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!