How is a static variable defined in Java?
In Java, static variables can be defined in two ways:
- Define static variables in a class using the static keyword. Static variables are shared among all instances of the class and can be accessed directly through the class name without needing to instantiate an object. For example:
public class MyClass {
public static int myStaticVariable;
}
In the given code, myStaticVariable is a static variable.
- Assigning values in a static block. A static block is a special block of code that is executed when a class is loaded and only executes once. Static variables can be initialized or assigned values in a static block. For example:
public class MyClass {
public static int myStaticVariable;
static {
myStaticVariable = 10;
}
}
In the above code, the static block assigns a value to myStaticVariable.
Static variables can be accessed directly through the class name, regardless of how they are defined. For example, by using MyClass.myStaticVariable.