What is the purpose of a final variable in Java?

Also, due to a quirk with how lexical closures work, variables must be final to use them within anonymous inner classes, which are very useful for event handlers

Answer by Jason Kinner:

Mutability is the little devil that makes code hard to debug. I love making member variables final. Also, due to a quirk with how lexical closures work, variables must be final to use them within anonymous inner classes, which are very useful for event handlers.

Like so many things in programming, final declares your intent for that variable never to change. It prevents you or future authors (including you, more than three weeks from now) from changing the system unintentionally. That's also a great reason to have unit tests.

What is the purpose of a final variable in Java?

Advertisements

Leave a comment

Filed under Life

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