Below you can see a static variable counter
in a Java class.
The question is when will this variable reset? For example, when I restart the program, computer. What are the other possible scenarios it can reset?
Another question is: what could be the reasons for this variable to increase by less than the number of times the function do() is executed? For example, could it be something with starting multiple processes of the class java Whatever
? Or could it be something with multiple threads/servers, etc?
class Whatever {
static int counter = 0;
function do() {
counter++;
//...
}
}
Additional question: If multiple threads execute function do(), how will the counter variable behave? It will be less than the number of times function do() was executed?
A static variable will be re-initialized when you restart the application.
According to the JLS:
If a field is declared static, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. A static field, sometimes called a class variable, is incarnated when the class is initialized
So this answers your first question. i.e.e exactly when the class is loaded :)
As per second question, nope. if the variable is declared private. Then the only access is via the method because of encapsulation.
Static variables lasts till the JVM is shutdown.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With