Câu hỏi phỏng vấn Java
Câu hỏi

What is static initializer in java?

Câu trả lời

A static initializer in Java, also known as a static block, is a block of code that is associated with the class and is executed exactly once when the class is first loaded into memory by the Java Virtual Machine (JVM). It is typically used to perform class-level initialization tasks that need to be executed only once during the application's lifetime.

Here's a detailed explanation of static initializers:

Purpose and Usage

The primary purpose of a static initializer is to initialize static variables or to perform setup operations that are required for the class. Since static variables are common to all instances of the class, they need to be initialized only once, which is exactly what the static initializer does. It can also be used to perform operations that are required to set up the environment for the class, such as loading native libraries, setting up logging, or initializing complex static fields that require more than a simple assignment.

Execution Timing

Static initializers are executed by the JVM at the time the class is loaded, which is before any objects of that class are created and before any static methods are invoked. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code[5][8].

Syntax

The syntax of a static initializer block is simple. It consists of the static keyword followed by a pair of braces enclosing the code that forms the static initializer:

java Copy
static {
    // Initialization code goes here
}

Characteristics

  • Static initializers cannot have a return value and cannot be called explicitly.
  • They cannot throw checked exceptions.
  • The this and super keywords, which are used to refer to the current object and the superclass respectively, cannot be used inside a static initializer because it is not associated with any object instance[4].
  • If a class has multiple static blocks, they will be executed in the order in which they are written in the class definition[4][10].

Example

Here's a simple example of a static initializer in Java:

java Copy
class DatabaseDriver {
    private static Connection connection;

    static {
        // Initialize the database connection
        connection = DriverManager.getConnection("jdbc:my...
middle

middle

Gợi ý câu hỏi phỏng vấn

junior

What will happen to the Exception object after exception handling?

expert

What is an efficient way to implement a singleton pattern in Java?

middle

What is a Constructor, Constructor Overloading and Copy-Constructor in Java ?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào