Why below code is not throwing any exception while final used?
final StingBuilder sb=new StingBuilder("Satya");
sb.append("Pune");
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With