1

I execute the following code and I wondered after seeing the result.

 public class Example3 {

    //section 01
    static int a =checker();

    //section 02
    static{
        System.out.println("inside the block");
    }

    //section 03
    public static int checker(){
        System.out.println("from checker");
        return 20;
    }

    //section 04
    public static void main(String[] args) {
        System.out.println(a);
        System.out.println("from main");
    }
}

expected output

from checker
20
from main

real output

from checker
inside the block
20
from main

I divided the piece of code int 4 sections like section 01...etc to explain the problem.

when we start the java program we are starting from the main method. So in the main method has in below.

System.out.println(a);  //step 01
System.out.println("from main"); //step 02

In the main method are two steps. I will explain in below that what I though.

Step 01

  1. go to the section 01.
  2. then move into the checker method(section 03)
  3. then print "from checker"
  4. then now "a" will takes the returned value of the checker method(a=20).

now step 01 finished.

Step 02

  1. will print "from main".

My problem is How additionally print "inside the block"?

Hilton
  • 337
  • 6
  • 19
  • 1
    Read the first answer here: [Static Initialization Blocks](https://stackoverflow.com/questions/2420389/static-initialization-blocks) - if that doesn't answer your question, clarify it please. – ernest_k Jan 30 '20 at 10:18
  • 2
    You have a _static initializer block_ that prints out something ("inside the block"). Why are you not expecting that output? It must be printed somewhere and sometime! Regarding the ordering of calls ... look at the linked question from @ernest_k. – Seelenvirtuose Jan 30 '20 at 10:20
  • 1
    @Seelenvirtuose How will be the flow of the above code? If can you give an answer it will be very helpful for me. – Hilton Jan 30 '20 at 10:23
  • 2
    Does this answer your question? [Java Static Initialization Order](https://stackoverflow.com/questions/19058766/java-static-initialization-order) – lugiorgi Jan 30 '20 at 10:32

1 Answers1

3

when we start the java program we are starting from the main method.

No, we are not. A class containing a main function is still a Java class. Because of that, it has to first be loaded and initialized by the ClassLoader, so the flow is:

  1. load the class in memory
  2. handle the static initialization in the order it occurs in the file so here:

    1. the a variable => prints from checker
    2. the static bloc => prints inside the block
  3. pass the control to the main function, actually printing the last 2 strings.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252