Static blocks - when they are executed

I am completely new to Java, and I wonder why my static block is not executing.

public class Main {

public static void main(String[] args) { 
    Account firstAccount = new Account();  
    firstAccount.balance = 100;
    Account.global = 200;  
    System.out.println("My Balance is : " + firstAccount.balance);
    System.out.println("Global data   : " + Account.global);

    System.out.println("*******************");
    Account secondAccount = new Account();
    System.out.println("Second account balance  :" + secondAccount.balance);
    System.out.println("Second account global   :" + Account.global);

    Account.global=300;
    System.out.println("Second account global   :" + Account.global);

    Account.add();  }
}

public class Account 
{
int balance;        
static int global;  

void display()   
{
System.out.println("Balance     : " + balance);
System.out.println("Global data : " + global);
}

static   // static block
{
    System.out.println("Good Morning Michelle");

}
static void add()  
 {
    System.out.println("Result of 2 + 3 " + (2+3));
    System.out.println("Result of 2+3/4 " + (2+3/4));  
}
public Account() {
    super();
    System.out.println("Constructor");

}
}

My conclusion:

Good Morning Michelle
Constructor
My Balance is : 100
Global data   : 200
*******************
Constructor
Second account balance  :0
Second account global   :200
Second account global   :300
Result of 2 + 3 5
Result of 2+3/4 2

I want to know why "Good Morning Michelle" did not appear when I logged in with my second account.

From my research, this static block should be executed every time a class is called (new account).

Sorry for the real beginner question. Michelle

+5
source share
2 answers

Your static block, which prints Good Morning Michelle, is a static initializer . They are run only once for each class when this class is first referenced. Creating a second instance of the class will not restart.

+8

. . :

+2

All Articles