Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why static block are executed later?

Tags:

java

static

P.S :

This question has been edited a few times as my previous code doesn't demonstrate the problem. There are some answers which may not make perfect sense against the edited question

I have a public class named Son.java

package com.t;

public class Son extends Father {

    static int i;

    static {
        System.out.println("son - static");
        i = 19;
    }

    {
        System.out.println("son - init-block"); 
    }

    public static void main(String[] args) {
        //Son s = new Son();
        int a[] = new int[2];
        System.out.println(a[5]);
    }

}

class Father {

    static {
        System.out.println("f - static");
    }
    {
        System.out.println("f - init-block");
    }
}

When I run the program for the 1st time:

Output is:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
    at com.t.Son.main(Son.java:19)
f - static
son - static

And later when I run this program (order of output is random)

Output is:

f - static
son - static
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
    at com.t.Son.main(Son.java:19)

I have read that static blocks are executed as the classes are initalised.

But why does the exception has come first here and then static block is executed?

I am using Eclipse too to run my program. Can somebody explain?

like image 208
Thinker Avatar asked Dec 19 '22 16:12

Thinker


2 Answers

The exception doesn't happen first, you are just seeing the printout of the exception first.

Had the exception happened first, you would never have seen the rest of the output.

The reason for this is that you have output to both System.err (from your exception) and System.out in your program. The order in which these are printed to the screen is not defined, so therefore you can get them in different order.

like image 196
Keppil Avatar answered Dec 22 '22 06:12

Keppil


Stack traces of uncaught exceptions are printed in System.err, which is an unbuffered stream. You print text to System.out which is a buffered stream and it is unpredictable whether it he buffer gets flushed before or after the stack trace is printed.

If you change all your print statements to System.err then the order of the output will become the order of printing, and it will always be the same order.

like image 23
Erwin Bolwidt Avatar answered Dec 22 '22 04:12

Erwin Bolwidt