1

In Java I've always seen Class variables (defined with keyword static) as equivalent of global variables in other languages such as C, defined inside a class to avoid name conflicts. In C you can refer a global variable from any function at any time it always exists while the program is running.

What about static variables in Java. Do they always exist? Do they always get loaded when they're referred? I wanna know if it's always safe when I use a static variable from a static method of another class.

Also does a static variable ever get destroyed?

Insignificant Person
  • 863
  • 2
  • 10
  • 24

1 Answers1

2

A static variable is initialized when the class is initialized, and so will always be valid (Initialization of Classes and Interfaces).

Initialization of a class consists of executing its static initializers and the initializers for static fields (class variables) declared in the class.

If the value of the static field is changed, and there are no other references to the previous value, then the previous value will be garbage collected. However, the reference itself will always exist, so if "safe" means "never access illegal memory", it is always safe (when using the Java language in general, not just in this case).