Satya
Satya

Reputation: 165

How the final keyword work with StringBuilder?

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

Upvotes: 3

Views: 5326

Answers (3)

Peter Lawrey
Peter Lawrey

Reputation: 533780

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.

Upvotes: 4

Abdelhak
Abdelhak

Reputation: 8387

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.

Upvotes: 7

Eran
Eran

Reputation: 394016

sb.append doesn't assign a new value to sb, only mutates the state of the instance already referred by sb. Therefore it is allowed, even for final variables.

If, on the other hand, you added a second assignment to sb, such as sb = null;, it wouldn't pass compilation.

Upvotes: 2

Related Questions