prred
prred

Reputation: 131

java anonymous statement or what it is called?

I would like to understand what is this called. I saw this program in oracle website. I have kept breakpoint and saw this statment is called after static block and before constructor is called.

What is signifiance of this statement ?

{
    System.out.print("y ");
}

In this code :

public class Sequence {
    Sequence() {
        System.out.print("c ");
    }

    {
        System.out.print("y ");
    }

    public static void main(String[] args) {
        new Sequence().go();
    }

    void go() {
        System.out.print("g ");
    }

    static {
        System.out.print("x ");
    }
}

Upvotes: 3

Views: 59

Answers (3)

Amir Afghani
Amir Afghani

Reputation: 38561

This is known as a static initialization block, or static initializer.

See: https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html

Personally, I prefer not to use them exactly for the reason stated in the documentation I sited.

There is an alternative to static blocks — you can write a private static method: The advantage of private static methods is that they can be reused later if you need to reinitialize the class variable.

Upvotes: 0

Hoopje
Hoopje

Reputation: 12952

It is an initializer block. It is executed whenever a new instance of a class is created. Most of the time you don't really need it, because instance initialization can also be put in the constructor. The initializer block is mainly there to initialize anonymous inner classes, for which you cannot define your own constructors (because to define a constructor you need the name of the class).

Upvotes: 0

M Sach
M Sach

Reputation: 34424

static {
        System.out.print("x ");
    }

Its the static block and its called whenever class is loaded. In general anonymous means which does not have any name like anonymous class are clases which does not have any name and their implementation is provided right at the place where it is required and can't be reused

 {
        System.out.print("y ");
    }

As Eran commented out ,It's an instance initialization block, and it's executed whenever an instance is created and is called even before constructor.

Upvotes: 1

Related Questions