A static variable is a variable that has been |allocated statically, meaning it’s value is known at compile time and its runtime is the duration of the program itself. This is contrast to automatic variables, whose storage is allocated on the stack and whose lifetime is controlled by the function calling it. This is also in contrast to dynamically allocated objects, who are allocated on the heap and whose lifetime is usually manually controlled or garbage collected.
Static Memory Allocation
In relation to memory allocation, static memory allocation is the allocation of memory at compile time, before the program is even executed.
Example
int x = 0;
int main() {
printf("Hello World");
}In the above example, x is a static variable. It is also a global variable. When the program compiles, the compiler would assign it an address in memory that would be hard coded into the program. Every function that uses this variable would therefore be accessing the same address in memory.
In Java
In java, static variables have a slightly more specific meaning. In Java, a variable being static means that it is class level as opposed to instance level. Memory for a static variable in Java will be allocated once, and is shared across all instances of that object. It can be accessed using the class name, as opposed to the instance name, and exists in memory as long as the class is loaded. It is generally used when a class needs some kind of constant or shared variable.