-2

Q1. Normally, after explicit initialization, the initialization block proceeds. this code source Does instance initialization occur after an initialization block?

Q2. When is the creation(memory upload) of the 'tmp' variable? Was it created before the initialization block?

class Test { 
 {
    tmp = 2;  
    System.out.println(this.tmp);
  }
  float tmp = 1;
}

class Main {
  public static void main(String[] args) {
    Test t = new Test();
    System.out.println("[Main] t.tmp : " + t.tmp);
    t.tmp = 100;
    System.out.println("[Main] t.tmp : " + t.tmp);
  }
}

[Result] 2.0 [Main] t.tmp : 1.0 [Main] t.tmp : 100.0

ejpark
  • 1
  • 1
  • Does this answer your question? [Java order of Initialization and Instantiation](https://stackoverflow.com/questions/23093470/java-order-of-initialization-and-instantiation) – Progman Nov 26 '22 at 15:28

1 Answers1

2

Refer to Java Language Specification (Java SE 17 edition), section 12.4.2 Detailed Initialization Procedure

Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.

According to the code in your question, the instance initializer is called first since it appears before the class member declaration. After that the member initialization is called.

Personally, I always declare the variables before the initializer blocks.

When the class is loaded, and before any initialization is done, variable tmp is created.

Abra
  • 19,142
  • 7
  • 29
  • 41