Today I had yet another opportunity to discover and interesting (and unexpected) difference between C# and Java. I was looking through some code and noticed a bizarre construct – some code sitting within a pair of curly braces that had no method name.

I’ve seen this kind of thing before and C# has support for anonymous methods and even anonymous classes and I even knew that Java supported similar things. I thought maybe it was a shortcut anonymous method (which it is, in a way), but as it turned out it was something more interesting – a static initializer.

Java has two different paradigms that allow developers to perform initialization code whereas C# only supports one. Both languages support the notion of constructors but Java also supports something a little different called an initializer. This code is actually invoked before the constructor. Technically it is invoked at the time the class is loaded. This can become a really important thing to be aware of, especially if you’re dynamically loading the class or you’re referencing it via something like MyClass.class, which is a pattern that should be familiar to Objective-C developers used to doing things like [MyClass class] (in C# we might do something like typeof(MyClass)).

Anyway, Java doesn’t support the notion of a static constructor like C# does, so the only way to initialize static fields or to perform other initialization code at class load (as opposed to instance load) time is with a static initializer. Java also supports an instance initializer which is actually fired before the classes constructor. This actually makes for really elegant looking code if there is initialization that needs to be done before any of a number of chained constructors needs to be invoked.

To demonstrate what these initializers look like (and the order in which they are executed), consider the following class:


public class Monster {

	private int localInt = 21;
	private static int staticInt = 225;

	// this will look crazy to a C# dev...
	// Instance Initializer
	{
		System.out.printf("I'm in an initializer: %d, %d%n",
				localInt,
				staticInt);
		localInt = 23;
		staticInt = 80;
	}

	// STATIC initializer
	static {
		System.out.printf("It's statically delicious: %d%n",
				staticInt);
		staticInt = 500;
	}

	public Monster() {
		System.out.printf("Monster: Constructed %d, %d%n",
				localInt,
				staticInt);
	}
}

When this code executes, it prints the following:

It’s statically delicious: 225
I’m in an initializer: 21, 500
Monster: Constructed 23, 80
Built a monster.

As I said in the previous post about Java, I’m sure this is old hat to you veteran Java developers but for me, it’s something else I didn’t know about Java that I simply never knew because I hadn’t spent the time examining the language to find out.