What is the purpose of a final variable in Java?

Answer by Doug Bell:

A few of the answers got this correct, but I'll answer more directly.

The only reason there are

final

variables in Java is to allow local variables to be referenced from inner classes scoped within the method.  Final variables were not added because of any consideration that declaring local variables as

final

was particularly useful.

The reason that a variable referenced from an inner class needs to be declared

final

is because the object(s) instantiated from the inner class receive only the value of the variable at instantiation.  The inner class instances do not have any reference to the variable.

Even if it were possible in Java to have a "pointer" to point to the primitive local stack variable, the lifetime of the instantiated object is often longer than the lifetime of the stack frame containing the value.

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