Initializer Blocks

Contact Us or call 1-877-932-8228
Initializer Blocks

Initializer Blocks

Class properties that are object types can be initialized with a newly constructed object.

public class MyClass {
	private Random rand = new java.util.Random();
	private MegaString ms = 
		new MegaString("Hello " + rand.nextInt(100));
	private int x = rand.nextInt(100);
	. . .
}

The MegaString class constructor code will run whenever a MyClass object is instantiated.

But what if the object's constructor throws an exception?

class MegaString{
	public MegaString(String s) throws Exception {
		. . .
	}
}
  • The MyClass code won't compile - you cannot put a property declaration into a try ... catch structure and there is no place to state that the property declaration throws an exception.

You can use an initializer block to handle this situation.

public class MyClass {
	private java.util.Random rand = new java.util.Random();
	private MegaString ms = null;
	{
		try { ms = new MegaString()"Hello " + rand.nextInt(100); }
		catch (Exception e) { . . . }
	}
	private int x = rand.nextInt(100);
	. . .
}

This is not absolutely necessary, since the initialization could be done in a constructor, where a try ... catch would be legal. But then it would need to be done in every constructor, which someone adding another constructor later might forget.

Initializers are run in the order in which they appear in the code, whether standalone initializers, or initializers in a field declaration so, in the above code:

  1. The Random object gets created for the first field.
  2. The MegaString gets the first generated random number.
  3. x gets the second generated random number.

Static Initializer Blocks

If a field is static, and is populated with a newly constructed object, that object's constructor code will run when the class loads. In our example, if we make the MegaString property static, its constructor will run when the class loads.

public class MyClass {
	private static MegaString sms = new MegaString("Goodbye");
	. . .
}
  • Again, this won't compile, but now there is no way even to defer the issue to the constructors, since the element is static.

You can use a static initializer block to handle this problem.

public class MyClass {
	private static MegaString sms = null;
	static {
		try { sms = new MegaString("Hello"); }
		catch (Exception e) { . . . }
	}
	. . .
}

Again, the initializers are run in the order in which they appear in the code, when the class is loaded.

Next