Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java and the use of the Final keyword

I'm new to Java having programmed in Delphi and C# for some time,. My question relates to the usage of the "final" keyword on a variable that holds an instantiated class when the variable declaration and instantiation both happen within the scope of the same method. e.g.

private String getDeviceID() {
   //get the android device id
   final TelephonyManager tm =                
     (TelephonyManager)GetBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
   final String deviceID = tm.getDeviceId();

   // log debug message containing device ID
   Log.d(LOG_CAT, "getDeviceID: " + deviceID);        

   return deviceID;
}

okay so I think I get the fact that "final" variables can only ever be assigned to once and cannot be changed due to the "final" keyword on each declaration, but don't both variables go out of scope when the method exits? and calling the method again will simply reallocate 2 new final variables that once again will go out of scope on method exit?

To me it seems kinda odd to be using the "final" keyword on these variables? unless I don't understand how they impact on local variables within a method's scope?

Can someone enlighten me as to what the impact of "final" is with regard to method scope, or is declaring these particular variables as final just a dumb ass thing that someone did?

like image 982
user1122206 Avatar asked Dec 21 '22 04:12

user1122206


2 Answers

final has no effect on scope.
It just prevents the variable from being re-assigned.

It serves as a signal to other developers that these variables will never change, and it prevents you from changing them by accident.
This is particularly useful in longer methods.

final is also required in order to use a variable in an anonymous inner class, since Java does not support true closures.

like image 77
SLaks Avatar answered Jan 04 '23 14:01

SLaks


These variables will indeed be garbage collected as soon as the GC will run when the method exits.

The final keyword is really there as a hint: this variable is instantiated once, you should not touch it in the body of the method itself. Similarly, declaring method parameters final forbids their reuse (which, imho, is a good thing).

Note however that the keyword only affects the object reference: it does not mean that methods on this object reference which modify its internal state will cease to work (typical example: setters).

Another note: when you omit the final keyword, and you don't modify the variable in the body of your method, the JVM is smart enough to optimize this case. So, you may omit it. Whether or not you use it, and where you use it, is a matter of taste/coding style.

And finally, it is good practice to declare public static variables as final: otherwise, anything can modify it! Think string constants etc.

like image 24
fge Avatar answered Jan 04 '23 12:01

fge