0

What is the need of initialization block in Java? How does it help in coding?

Do we just add a set of curly braces extra in our code?

Eg:

public class GFG
{
    // Initializer block starts..
    {
        // This code is executed before every constructor.
        System.out.println("Common part of constructors invoked !!");
    }
    // Initializer block ends

    public GFG()
    {
        System.out.println("Default Constructor invoked");
    }

    public static void main(String arr[])
    {
        GFG obj1;
        obj1 = new GFG();

    }
}

1 Answers1

0

There are two types of initializer blocks. You have a static initializer block which runs on creation of class. Its syntax is

static {
    //stuff here
}

The other one is instance initialization block which runs when you instantiate an object. Its syntax is

{
    //stuff here
}

If initialization requires some logic (for example, error handling or a for loop to fill a complex array), simple assignment is inadequate. Instance variables can be initialized in constructors, where error handling or other logic can be used. To provide the same capability for class variables, the Java programming language includes static initialization blocks.

This is to answer your question on when you should use them. You basically use them to initialize a variable with some kind of specific logic. It's from the official Oracle documentation.

Nothing Nothing
  • 126
  • 1
  • 8