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


Immutables

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. 

Mutables

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.

Examples

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 
builder.append("Bar"); 
Advertisements

About Gaurav

I'm Gaurav; friends call me Teddy, n i'm shivi fr my family!! A java enthusiast who likes experimenting with what he knows. View all posts by Gaurav

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: