The static modifier can modify variables, constants, methods, and code blocks, called static variables, static constants, static methods, and static blocks of code, respectively.
1.static variables
In Java, if you want the value of a variable to be shared by all objects, you can declare the variable as a static variable (also called a class variable). Static variables allocate only a block of storage space when the class is loaded, and all objects of this class can manipulate this chunk of storage, providing shared variables for all class instances. When an object modifies the variable, the other object will then use the variable to be the changed data. The syntax for declaring a static variable is as follows:
[Permission control] static member variable type member variable name;
The syntax for accessing static variables is as follows:
Class name. static member variable name (not homogeneous)
Static member variable name (in the same class, can also be accessed using the above method)
2.static Constants
In Java, a variable that uses the final modifier is a constant, and if both final and static are decorated with a constant, the constant is a static constant. Static constants are generally common to all objects, so there are many cases where you declare constants as static.
The specific syntax format for declaring static constants is as follows:
[Permission control] static final constant type constant name = constant value;
The specific syntax format for accessing static constants is as follows:
Class name. Static constant name (not homogeneous)
Static constant name (in the same class, can also be accessed using the above method)
3.static method
In Java, a method that is modified by static is called a static method or a class method. Static methods cannot directly access the non-static member variables and member methods of the owning class, only the static member variables and member methods of the owning class. The syntax is as follows:
[Permission control] static return type member method name ([parameter list]) {method body;}
The syntax for accessing a static method is as follows:
Class name. static method Name ([argument list]) (not homogeneous)
static method name ([argument list]) (in the same class, can also be used for the above method access)
4.static code block
In Java, if some code (such as initialization data) must be executed when the program starts, a static block of code is required. Static code blocks are executed automatically once the class is loaded, and if a class has more than one static block of code, it executes sequentially in the order in which they appear in the class.
Example:
public class test{static int i = 1;static{system.out.println ("hello,static");} Static{system.out.println ("Current value of I" + i++);} public static void Main (string[] args) {System.out.println ("value of current I" + i++);}}
Java keyword static