Showing posts with label static initialization. Show all posts
Showing posts with label static initialization. Show all posts

Sunday, 15 May 2011

Static initialization block in java

You initialize a static field either by supplying an initial value or by using a static initialization block. You have already seen the first mechanism:
static int nextId = 1;


If the static fields of your class require complex initialization code, use a static initialization block.

Place the code inside a block and tag it with the keyword static. Here is an example. We want the employee ID numbers to start at a random integer less than 10,000.

// static initialization block

static

{

Random generator = new Random();

nextId = generator.nextInt(10000);

}




Static initialization occurs when the class is first loaded. Like instance fields, static fields are 0, false, or null unless you explicitly set them to another value. All static field initializers and static initialization blocks are executed in the order in which they occur in the class declaration.

Saturday, 14 May 2011

Difference between static and init block

The static block is only loaded when the class object is created by the JVM for the 1st time whereas init {} block is loaded every time class object is created. Also first the static block is loaded then the init block.

public class LoadingBlocks {

static{
System.out.println("Inside static");
}

{
System.out.println("Inside init");
}
public static void main(String args[]){
new LoadingBlocks();
new LoadingBlocks();
new LoadingBlocks();
}
}



Output:

Inside static
Inside init
Inside init
Inside init


So static block is initialized only once, that is it is per class basis, whereas init block is per object basis.

Friday, 15 April 2011

Double Brace Initialization in Java!

Few days back I came to know about a different way of initializing collections and objects in Java. Although this method of initialization has been there in Java since quite a few years now, very few people actually knows about it or have used it in their code. The technique is called Double Brace Initialization technique in Java.
Let us see first how we will initialize an ArrayList in Java by “normal” way:

List<String> countries = new ArrayList<String>();
countries.add("Switzerland");
countries.add("France");
countries.add("Germany");
countries.add("Italy");
countries.add("India");

Above code snippet first creates an object of ArrayList type String and then add one by one countries in it.

Now check the Double Brace Initialization of the same code:
List<String> countries = new ArrayList<String>() {{
add("India");
add("Switzerland");
add("Italy");
add("France");
add("Germany");
}};

How does this works?

Well, the double brace ( {{ .. }} ) initialization in Java works this way. The first brace creates a new AnonymousInnerClass, the second declares an instance initializer block that is run when the anonymous inner class is instantiated. This type of initializer block is formally called an “instance initializer”, because it is declared withing the instance scope of the class — “static initializers” are a related concept where the keyword static is placed before the brace that starts the block, and which is executed at the class level as soon as the classloader completes loading the class . The initializer block can use any methods, fields and final variables available in the containing scope, but one has to be wary of the fact that initializers are run before constructors.
If you have not understood the concept, try executing following code and it will make things clear for you.


public class Test {
public Test() {
System.out.println("Constructor called");
}
static {
System.out.println("Static block called");
}

{
System.out.println("Instance initializer called");
}

public static void main(String[] args) {
new Test();
new Test();
}
}

Output:

Static block called
Instance initializer called
Constructor called
Instance initializer called
Constructor called
Thus the instance initializer code will be called each time a new instance of object is created.

Tuesday, 12 April 2011

Some points to note about enums

There are few things which could probably be improved in the coming versions of Java.

  • Currently null can be passed as a method parameter or assigned where an enum is expected. A compile-time verification for null enum assignment would probably avoid all those extra null checks that we need to incorporate in our code.
  • Static fields within enums cannot be accessed in its constructor. But, static methods are allowed to be invoked. The compiler enforces verification only for static fields and not methods.
  • However, enum constructors are invoked before static initialization is performed and hence the static fields would not be initialized. So, if you invoke static methods from the constructor which inturn access static fields, they would all be un-initialized.

Friday, 18 February 2011

Static initializer block is called only when the class is being loaded in JVM

public class StaticTest {
static {
System.out.println("Hi there");
}
public void print() {
System.out.println("Hello");
}
public static void main(String args []) {
StaticTest st1 = new StaticTest();
st1.print();
StaticTest st2 = new StaticTest();
st2.print();
}
}
So this class prints :
Hi there
Hello
Hello

Note that Hi there is printed only once.

Thursday, 17 February 2011

Static variable initialization

Static variables if not initialized are initialized to 0.

public class Test {
static int age;
public static void main (String args []) {
age = age + 1;
System.out.println("The age is " + age);
}
}
So the above code compiles and runs printing out The age is 1.