Posts

Showing posts with the label initialization

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...

Java Puzzle : Integer Initialization

Here is a simple program which instantiate Integer object using primitive int values with all possible ways, new operator, AutoBoxing , Integer.valueOf() . 1: package com.test; 2:   3: public class IntegerPuzzle { 4: public static void main(String[] args) { 5: Integer a = new Integer(100); 6: Integer b = new Integer(100); 7: Integer c = 100; 8: Integer d = 100; 9: Integer e = Integer.valueOf(100); 10: Integer f = 150; 11: Integer g = 150; 12: 13: System.out.println( "a = b ? " + (a==b)); 14: System.out.println( "c = d ? " + (c==d)); 15: System.out.println( "d = e ? " + (d==e)); 16: System.out.println( "a = c ? " + (a==c)); 17: System.out.println( "f = g ? " + (f==g)); 18: } 19: } What would be the output of  this program ?