Skip to main content

Class initialization

  • Although we tend to think of initialization in terms of assigning values to variables, initialization is so much more. 
  • For example, initialization might involve opening a file and reading its contents into a memory buffer, registering a database driver, preparing a memory buffer to hold an image's contents, acquiring the resources necessary for playing a video, and so on.
  • Java supports initialization via language features collectively known as initializers.
  • Class initialization is different from Object initialization and it happens before Object initialization.


 

  • Class Initialization
    • A program contains no of classes, before the execution of java program the class loader loads the public class having the PSVM.
    • Then the byte code verifier verifies the class.
    • Then class initializes.
    • The class fields are set to default values.
    • For Example:


       

      • static boolean b;//flase
      • static byte by;//0
      • static char c;//
      • static double d;//0.0
      • static float f;//0.0
      • static int i;//0
      • static long l;//0
      • static short s;//0
      • static String st;//null


         

  • We can also explicitly assign values to the class fields.
  • Those values are assigned to the fields just after the class is loaded and before any user defined method including main executes.
  • This initialization is done using <clinit>method of the JVM. It uses machine level instructions to assign those values.
  • Although a subsequently declared class field can refer to a previously declared class field, the reverse is not true: You cannot declare a class field initializer that refers to a class field declared later in source code. In other words, Java does not permit forward references with class field initializers, as the following code fragment demonstrates:
    • static int second = 1 + first;
    • static int first = 3;
  • In the cases when you need to read the contents of the file before the main method executes then we need to use the static block.
    • static
    •    {
    •       System.out.println ("Acquiring filenames");
    •       filenames = new File (".").list ();
    •       System.out.println ("Filenames acquired");
    •    }
  • Class block initializers are useful. For example, Sun's JDBC (Java Database Connectivity) API uses class block initializers to simplify database driver registration. Consider the following code fragment:
    • Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
  • Any variable declared in the block is having the scope only upto that block.
  • JVM allows us to declare any constant field without any explicit initializer, but u have to initialize it before its first use.
    • class ClassInitializationDemo5
    • {
    •    final static double PI;
    •    static
    •    {
    •       PI = 3.14159;
    •       int i;
    •       for (i = 0; i < 5; i++)
    •            System.out.println (i);
    •    }
    •    static int j = i;//this vl cause problem as the I is local to that block
    •    public static void main (String [] args)
    •    {
    •       System.out.println ("PI = " + PI);//this vl show 3.14 as the initialization is done in static block
    •    }
    • }
  • When a class hierarchy is involved, the compiler creates a separate<clinit> method for each class in that hierarchy. At runtime, the JVM loads all hierarchy classes and calls their <clinit> methods in a top-to-bottom order. 

Popular posts from this blog

Primitive Obsession with Example

Primitive Obsession is the name of a code smell that occurs when we use primitive data types to represent domain ideas. For example, we use a string to represent a message or an integer to represent an amount of money. For Example: Code with Primitive Obsession // primitiveObsession.java public class primitiveObsession { public static void main ( String args []) { Integer [] cityPopulations = { 13000000 , // London 21903623 , // New York 12570000 , // Tokyo 1932763 , // Stockholm 1605602 , // Barcelona 4119190 // Sydney }; for ( Integer cityPopulation : cityPopulations ) { System . out . println ( cityPopulation ); } } } public class City { private final String name ; private final int population ; private final Continent continent ; public String getName () { return name ; } public int getPopulation () { return population ; } public Continent ge...

Singleton Pattern

Lazy Initialization :- The instantiation of an object can be delayed until it is actually needed. Usage: This especially beneficial when the constructor is doing a costly job like, accessing a remote database. Example: This code demonstrates how the Singleton pattern can be used to create a counter to provide unique sequential numbers, such as might be required for use as primary keys in a Database:   Sequence.java   public class Sequence { private static Sequence instance; private static int counter; private Sequence() { counter = 0; // May be necessary to obtain // starting value elsewhere... } public static synchronized Sequence getInstance() { if(instance==null) // Lazy instantiation { instance = new Sequence(); } return instance; } public static synchronized int getNext() { return ++counter; } }   Some things to note about this implementation: Synchronized methods are used to ensure that the class is thread-safe. This class cannot be subclassed because the constructor is private ...

Overview of EJB and Lifecycle

The container is responsible for loading, activating, and in general maintaining the "life-cycle" of objects it provides. EJB have a fairly complex life-cycle. There are several kinds of EJB: Session Beans: These may be either stateful or stateless, and are primarily used to encapsulate business logic, carry out tasks on behalf of a client, and act as controllers or managers for other beans.   Entity Beans: Entity beans represent persistent objects or business concepts that exist outside a specific application's lifetime. They are typically stored in a relational database. Entity beans can be developed using bean-managed persistence, which is implemented by the developer, or container-managed persistence, implemented by the container.   Message-Driven Beans : Message-driven beans listen asynchronously for Java Message Service (JMS) messages from any client or component and are used for loosely coupled, typically batch processing.