Why is a static block executed later?

PS:

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 first time:

Output:

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 (output order random)

Output:

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

I read that blocks staticare executed as classes are initialized.

But why is the first exception raised here and then a static block executed?

I use Eclipseto run my program. Can someone explain?

+4
source share
4 answers

The exception does not occur at first, you just see the listing of the exception in the first place.

If the exception occurred first, you would never see the rest of the output.

, System.err ( ), System.out . , , , .

+10

System.err, . System.out, , , .

System.err, , .

+3

@ Keppil .


-... erm... .

:

Eclipse .

, " "... , → < < . , stdout/stderr , "Eclipse".

, stderr stdout, , - . , , , syscall select ... , . , , .

Eclipse, Eclipse, , . , read syscalls, , , , . , select... .

, , stdout/stderr Eclipse, "" .

0

As asser said, mainbelongs to the class Sonand spreads Father. I changed the code a bit, so I was able to compile.

    class Father {
    static{
        System.out.println("f - static");

    }
}

public class Son extends Father {
    static {
        System.out.println("son - static");
    }

public static void main(String[] args) throws ArrayIndexOutOfBoundsException{
        int a[] = new int[2];
        System.out.println(a[3]);
    }
}

And the result: -

f - static
son - static
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
    at kanwal.Son.main(Son.java:20)

It works exactly as intended.

EDIT: - This answer was made before the OP edited the question.

-2
source

Source: https://habr.com/ru/post/1533112/


All Articles