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?
final
is likeconst
in c for primitives and references.There's nothing special about the scope of a
final
local variable or parameter.Declaring a local variable or parameter as
final
doesn't really do much and is rarely necessary. There are basically two reasons for it:final
is going overboard.final
. This is a kluge in the Java language; its purpose is to prevent code in the inner class from trying to modify the variables or parameters after they are no longer alive.