Posts

Showing posts with the label lazy

Lazy initializing your code

Many time we have static fields in our Java classes. These fields are get initialized with loading of your classes and all other static fields. But many time its not the urgent to initialize few of the fields while loading the class itself. Here the concept of lazy initialization comes in picture. Consider the code below public class LazyInitilaizationTest { public static String[] field = getStringContent(); static { System.out.println( "Loading Class" ); } public static String[] getStringContent(){ System.out.println( "Initializing field" ); return new String[]{}; } public static void main(String[] args) { System.out.println( "Accessing Field" ); System.out.println(field); } } Here the class has private & static field which gets initialized by invoking getStringContent () method. Running above class prints following output Initializing field Loading Class Acce...