I know how a static init block works.
Can anyone please tell me some typical uses of it.
I know how a static init block works. Can anyone please tell me some
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
When you want to initialize one or more static variables in one place
It is useful, because you can apply exception handling, which is not possible with the in-line initialization.
For example:
can be initialized with
Another application is complex initialization. For example, if an item requires more than one line of code to be initialized. Let’s say you have a configuration:
A third usage is to initialize some external API infrastructure. One example from my current project:
But, as Mykola Golubyev noted, static initialization blocks make code less readable, so use them with caution. static methods do the same thing more transparently.