Modifying A Final Variable

Have you ever tried to update a final variable? Or it always has been holy and heavenly enough to try and update?

Well I came across this piece of information a few months ago, I so wanted to read the whole documentation of Java, hoping to invalidate my assumption that final variables couldn’t be touched.

A final variable can be modified unless it is immutable


Yes, a final variable can be modified, but only if it is a mutable object. So primitives (int, boolean, char e.t.c.) which are immutable cannot be modified. 


One can surely update a mutable object declared final, but cannot update its reference. Thus objects like StringBuilder can be modified (remember append method?) unless you are updating the reference of the object.


final int intVariable = 0; 
final String stringVariable = "foo"; 
final StringBuilder builderVariable = new StringBuilder("foo"); 

// exception, as updating immutable primitive 
intVariable = 0; 
// exception, string is immutable 
stringVariable = "foo"; 
// exception, trying to reference of mutable object 
builderVariable = new StringBuilder("foo"); 
// works, as mutable object is modified and reference is not updated 

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: