static keyword

The static keyword creates class-level variables and methods.
Static means that the memory space determined when the class is loaded does not change.
You can use static variables and methods without creating an object like this:

  • ClassName.staticVariable
  • ClassName.staticMethod()

The main method is the static method.

The class loader must first load bytecodes into memory to run a Java program. JVM allocates memory space for static variables when the class loader a bytecode into memory. The memory space to which a static variable does not change until the end of the program.

Note: This memory space is not an area of heap memory to which JVM allocates objects. -- Every time the new keyword runs, JVM allocates the object's instance variables to the heap memory area --

You can not use instance variables in static methods. It does not make sense to refer to the properties of an object that it can not create. You will get a compile error if you add the following to the main method of the student class.

public static void main(String[] args) {
  absentNum++;
}

Conversely, using static variables or methods in instance methods is no problem.

Suppose students must pay a fine if they are absent or late or leave early. The fine is $ 3 for absences and $ 1 for late or leaving early.

Students must put a fine in the penalty box. The penalty box is only one, and all students share. It is not a property that distinguishes students from students. How implement the penalty box in the code? An approach is to make the box a static variable that all student objects share.

public class Student {
  static int penaltyBox;

  public void absent() {
    this.absent++;
    Student.penaltyBox += 3;
  }
  //..Omit
}    

The following is an example of a static variable that stores the total number of users.

package net.java_school.user;

public class User {

  public static int totalUser;
  private String id;
    
  public User(String id) {
    this.id = id;
    total++;
  }

  public static void main(String[] args) {
    User user1 = new User("hong1440");
    User user2 = new User("im1562");
    User user3 = new User("jang1692");
        
    System.out.println("Total Users : " + User.totalUser);
  }
}
C:\ Command Prompt
C:\Users\John>java net.java_school.user.User
Total Users : 3

Singleton pattern

The singleton pattern is the design pattern to use when you need to create only one object.

Suppose there should be only one dinner table at home.

package net.java_school.home;

public class DinnerTable {

  private static DinnerTable instance = new DinnerTable();
    
  public static DinnerTable getInstance() {
    return instance;
  }
    
  private DinnerTable() {}
    
  //..Omit
}
  1. Let JVM creates an object in the heap memory and assigns its reference to the private static variable.
  2. Declare only a private constructor to prevent the constructor from being called from outside.
  3. Create one public method to expose the reference to the outside.

If implemented as above, an instance is maintained as one until the program ends.

Initialization Order

JVM initializes variables when it allocates them to memory space.
If the code does not have an initial value, the Boolean type is false, the numeric type is 0, and the reference type is null.

JVM initializes instance variables when it allocates them in the heap memory.

The initialization order is static variables, instance variables, and constructors.

Static variables and static blocks are at the same level.
So the previous one in the code is initialized first.

For instance blocks, the compiler adds the implementation of the instance block to every constructor. Thus, instance blocks precede constructors.

A.java
package net.java_school.classvar;

public class A {

  public A() {
    System.out.println("A() has executed.");//4,9,14
  }
}
B.java
package net.java_school.classvar;

public class B {
  private A a = new A();//3,8,13
    
  {
    System.out.println("B instance block has executed.");//5,10,15
  }
    
  static {
    System.out.println("B static block has executed.");//1
  }
    
  private static B b = new B();//2

  private B() {
    System.out.println("B() has executed.");//6,11
  }
    
  public B(int a) {
    System.out.println("B(int) has executed.");//16
  }

  public static void main(String[] args) {
    new B();//7
    new B(1);//12
  }
}
C:\ Command Prompt
C:\Users\John>java net.java_school.classvar.B
B static block has executed.
A() has executed.
B instance block has executed.
B() has executed.
A() has executed.
B instance block has executed.
B() has executed.
A() has executed.
B instance block has executed.
B(int) has executed.
References