Junior
Where is the initialization of static and non-static fields allowed?
sobes.tech AI
Answer from AI
In Java, initialization of static and non-static fields is allowed in different places:
-
Static fields (static):
- Can be initialized directly at the declaration in the class.
- Can also be initialized in static initialization blocks (
static { ... }).
-
Non-static fields (instance):
- Can be initialized at the declaration in the class.
- Can be initialized in the class constructor.
- Can be initialized in non-static initialization blocks (
{ ... }).
Example:
public class Example {
static int staticField = 10; // initialization at declaration
int instanceField = 5; // initialization at declaration
static {
staticField = 20; // static initialization block
}
{
instanceField = 15; // non-static initialization block
}
public Example() {
instanceField = 25; // initialization in constructor
}
}
Thus, static fields are initialized once when the class is loaded, while non-static fields are initialized each time an object is created.