static {}
时间: 2023-03-04 15:36:05 浏览: 61
In Java, a static block is a special type of block that is defined inside a class and is executed only once, when the class is loaded into memory by the Java Virtual Machine (JVM).
The syntax for a static block is as follows:
```
static {
// code to be executed
}
```
The code inside the static block is executed only once, when the class is first loaded into memory. This makes it useful for performing one-time initialization of static variables, or for setting up any static resources that need to be initialized before the class can be used.
Here's an example of a static block that initializes a static variable:
```
public class MyClass {
public static int myStaticVariable;
static {
myStaticVariable = 42;
}
}
```
In this example, the static block sets the value of `myStaticVariable` to 42 when the class is loaded into memory. This ensures that the variable is initialized before it is used in any other part of the program.