CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Classes

Objects and Classes
Static fields and methods
Initialization block

How to code a static initialization block

  • To initialize the static variables of a class, you typically code the values in the declarations. But if a variable can't be initialized in a single statement, you can code a static initialization block that's executed when another class first calls any method of the static class.
  • When a class is loaded, Java initializes all static variables and constants of the class. Then, it executes all static initialization blocks in the order in which they appear.
  • A class is loaded when one of its constructors or static methods is called.

The syntax for coding a static initialization block

public class className
{
    // any field declarations

    static
    {
      // any initialization statements for static fields
    }

    // the rest of the class
Previous | Code | Call | Initialization block | Use | Next