0
I have a doubt that has been troubling me for a long time:
What is the advantage of creating a static and final variable (both private and public)?
If I have a primitive variable or simple classes (String for example), they have final values and are private. They should be static?
In the previous case, what is the impact of memory on an Android device?
As far as I know, creating variables of types that interact with the context of the application can happen a memory leak, so I know this is a "bad practice". However, what about simpler variables?
*Note: I installed a plugin in Android Studio that told me to put end even on local variables and that are argument. I did not understand the real need, and so I did not hesitate to ask here, for who knows.
The reason the compiler requires a local variable to be
final
has to do with the fact that it’s used in a Inner class. The issue of Context has to do with the destruction/recreation of Activities. If there is a static reference to an Activity/Context when it is destroyed/recreated it will not be collected by the Garbage Collector, giving rise to a memory leak.– ramaral
So that’s the thing about Context. However, as for the final variable, the plugin suggests me to use even the variables that are arguments in a constructor! I don’t use them in a nested class, only pass such variables to the private class...
– Guilherme Ramos
This has to do not only with the last paragraph of the answer, but also with the "good practice" that values passed to the constructor should not be changed.
– ramaral
Yes, I get it. But I thought it was more about security or memory efficiency
– Guilherme Ramos
@GH_ The memory for a variable Static (class variable) is only allocated once. A variable is not Static (instance variable) is allocated by each instance.
– ramaral
@ramaral, then the best practice, would be (if the variable is private and static only) nullify its values once Activity was destroyed? or has nothing to do with it? If the variable is final, static and private, would it be basically just accumulating memory (if there are more activities)? Confer?
– Guilherme Ramos
A static variable, whether private or public, final or not, if initialized, its value (memory) is maintained throughout the life of the application. A non-static variable has its memory occupation released when it is no longer referenced and when the Garbage Collector understands. If you have static variables that reference Context(Activity is a Context) you must "undo them" before Activity is destroyed.
– ramaral