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

Hibernate Notes

  The Hibernate project has the structure as shown in the figure as above. We need one hibernate.cfg.xml file for hibernate configuration which handles connection pulling and other stuff like driver name, username of the database, password of the database, and the following properties.. Hibernate.cfg.xml <?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory>   <property name="hibernate.connection.driver_class"> com.mysql.jdbc.Driver</property>   <property name="hibernate.connection.url"> jdbc:mysql://localhost/hibernatetutorial </property>   <property name="hibernate.connection.username"> root </property>   <property name="hibernate.connection.password"></pr