Java Static Block Tutorial

In this section, we will learn what the static block is and how to use it in Java.

Note: we’re assuming you’re already familiar with static variables in Java.

What is static block in Java?

Static blocks are blocks of codes that the compiler will automatically execute them. We can use them to initialize static variables that need multiple lines of code to be fully initialized.

When we want to initialize a static variable, we can directly and in the place where the variable is being declared, initialize it right away. In this case, we have only one statement and basically we can use the assignment operator to initialize the variable.

But the problem here is that not all static variables can be initialized in just one statement!

Take the example below:

Let’s say we have a class named `Person` and it has a body like this:

public class Person {
    private String name;
    private String lastName;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

Now there’s another class named `Child` that has a static variable of type `Person` like this:

public class Child {
    public static Person prs = new Person();

}

As you can see, we didn’t completely initialized the variable! All we did was, creating an object and assign it to this static variable.

But the instance of the Person class still needs to have `name` and `lastName` values set for its attributes.

This is possible by calling the `setName()` and `setLastName()` methods of this object, but we can’t use these methods unless we call the `prs` object inside the body of a static method! Unfortunately, in this `Child` class there’s no static method to use! Even if there was one, that puts work on developers to make sure call that method at runtime somewhere in the program before moving and use the `Child` class for other purposes!

A better work would be to use `static block`!

How to declare a static block in Java?

First of all, a block is the area between the open brace `{` and its corresponding close brace `}`.

Now to create a static block, all we need to do is to put the keyword static in front of open brace like this:

static {

//body…

}

That’s how we can create a static block.

Note: a static block is declared outside of any method and in the body of the class itself.

Example: creating single static block in Java

Let’s refactor the `Child` class and see the use of a static block in practice:

public class Child  {
    public static Person prs = new Person();
    static {
        prs.setLastName("Doe");
        prs.setName("John");
    }
}

As you can see, we have created one static block and now inside this block we can fully initialize the `prs` object.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies