Java: When is a static initialization block useful?

119,545

Solution 1

A static initialization blocks allows more complex initialization, for example using conditionals:

static double a;
static {
    if (SomeCondition) {
      a = 0;
    } else {
      a = 1;
    }
}

Or when more than just construction is required: when using a builder to create your instance, exception handling or work other than creating static fields is necessary.

A static initialization block also runs after the inline static initializers, so the following is valid:

static double a;
static double b = 1;

static {
    a = b * 4; // Evaluates to 4
}

Solution 2

You can use try/catch block inside static{} like below:

MyCode{

    static Scanner input = new Scanner(System.in);
    static boolean flag = true;
    static int B = input.nextInt();
    static int H = input.nextInt();

    static{
        try{
            if(B <= 0 || H <= 0){
                flag = false;
                throw new Exception("Breadth and height must be positive");
            }
        }catch(Exception e){
            System.out.println(e);
        }

    }
}

PS: Referred from this!

Solution 3

A typical usage:

private final static Set<String> SET = new HashSet<String>();

static {
    SET.add("value1");
    SET.add("value2");
    SET.add("value3");
}

How would you do it without static initializer?

Solution 4

Exception handling during initialization is another reason. For example:

static URL url;
static {
    try {
        url = new URL("https://blahblah.com");
    }
    catch (MalformedURLException mue) {
        //log exception or handle otherwise
    }
}

This is useful for constructors that annoyingly throw checked exceptions, like above, or else more complex initialization logic that might be exception-prone.

Solution 5

We use constructors to initialize our instance variables conditionally.

If you want to initialize class/static variables conditionally, and want to do it without creating an object (constructors can only be called when creating an object), then you need static blocks.

static Scanner input = new Scanner(System.in);
static int widht;
static int height;

static
{
    widht = input.nextInt();
    input.nextLine();
    height = input.nextInt();
    input.close();

    if ((widht < 0) || (height < 0))
    {
        System.out.println("java.lang.Exception: Width and height must be positive");
    }
    else
    {
        System.out.println("widht * height = " + widht * height);
    }
}
Share:
119,545

Related videos on Youtube

Adam Matan
Author by

Adam Matan

Team leader, developer, and public speaker. I build end-to-end apps using modern cloud infrastructure, especially serverless tools. My current position is R&amp;D Manager at Corvid by Wix.com, a serverless platform for rapid web app generation. My CV and contact details are available on my Github README.

Updated on December 22, 2021

Comments

  • Adam Matan
    Adam Matan over 2 years

    What's the difference between initialization within a static block:

    public class staticTest {
    
        static String s;
        static int n;
        static double d;
    
        static {
            s = "I'm static";
            n = 500;
            d = 4000.0001;
        }
        ...
    

    And individual static initialization:

    public class staticTest {
    
        static String s = "I'm static";
        static int n    = 500;
        static double d = 4000.0001;
    
        ....
    
    • Platinum Azure
      Platinum Azure over 12 years
      You're only using assignments in the static initialization block, so of course those could be done using static variable assignment. Have you tried seeing what happens if you need to execute non-assignment statements?
    • qrtt1
      qrtt1 over 12 years
      It is a good place to load classes or load native library.
    • Bill K
      Bill K over 6 years
      Note that static variables should be avoided and therefore static initialization blocks are generally not a great idea. If you find yourself using them a lot, expect some trouble down the line.
  • gawi
    gawi over 12 years
    While what you are saying is true, it does not demonstrate the necessity of static initializer block. You can just move you ab declaration below the declaration of b.
  • Paul Bellora
    Paul Bellora over 12 years
    Answer: Guava :) +1
  • George Hawkins
    George Hawkins over 12 years
    Doing "b = a * 4;" inline would only be a problem if b were declared before a, which is not the case in your example.
  • Rich O'Kelly
    Rich O'Kelly over 12 years
    @GeorgeHawkins I was only trying illustrate that a static initialiser runs after inline initialisers, not that an equivalent couldn't be done inline. However, I take your point and have updated the example to (hopefully) be clearer.
  • TWiStErRob
    TWiStErRob over 7 years
    Another answer without additional libraries: create a static method that encapsulates the initialization of SET and use the variable initializer (private final static Set<String> SET = createValueSet()). What if you have 5 sets and 2 maps would you just dump all of them into a single static block?
  • Bill K
    Bill K over 6 years
    Just for fun I might point out that your first example could just as easily be "static double a=someCondition?0:1;" Not that your examples aren't great, I'm just sayin... :)
  • shmosel
    shmosel about 6 years
    Reading stdin in a static initializer is a pretty awful idea. And System.out.println("B * H"); is pretty useless. And the answer itself is pretty vague. OP didn't mention constructors or instance variables.
  • Michael
    Michael about 6 years
    This is just an example that shows what a static initializer is and how it is used. OP didnt ask for constructors or instance variables but in order to teach him the difference of static initializer from constructor he needs to know that. Otherwise he would say "Why dont i just use a constructor to initialize my static variables?"
  • Amit Amola
    Amit Amola about 3 years
    So initializing variables as static and then working with them inside the static block worked but why am I getting an error if I initialize the variables as static int B, etc inside the static block?
  • Rich O'Kelly
    Rich O'Kelly about 3 years
    Hi @AmitAmola, thanks for the comment / question - if I've understood correctly this will be because it's not valid to declare class variables within code blocks (eg declaring variables as static inside a code block isn't valid Java, they can only be declared as static in the class), but if I've misunderstood, it'd be worth posting this as a separate question on stack overflow along with your code. HTH