Wednesday, September 20, 2006

Static Initialization Block

You cannot initialize class variables using a constructor. A useful way of initializing class variables is to use a static initialization block. It saves memory because only one copy of the static initialization block is store for all instances of the class.

A static initialization block begins with the static keyword and is encapsulated in braces. Here is an example,
static {
try {
charsInFile = 0;
FileReader in = new FileReader("TestStaticBlock.java");
while(in.read() != -1) {
charsInFile++;
}
} catch (Exception e){
}
System.out.println("Finished static initialization block: " + charsInFile);
}

No comments: