
Initialization Block
Normally, you put code to initialize an instance variable in a constructor. However, there in an alternative to
using a constructor to initialize instance variables. It is called the initialization block. An initialization block is
a normal Java code block (code enclosed in braces { }) without any name or modifier.
public class Car {
String color;
String type;
{
color = "red";
type = "sedan";
}
}
The Java compiler copies the initialization block into every constructor, even the Default constructor. Code
from the initialization block gets executed before the rest of the code in the constructor. Furthermore, you can
have multiple initialization blocks in a class. The initialization blocks execute in the sequence in which they
appear in the class.
So why initialization blocks? Why not just use constructors? The Java programming language usually gives
you lots of options for creating your code/applications. One reason is that initialization blocks can be used to
share initialization code between multiple constructors. Secondly, as shown in the example above, the
initialization block provides a way to have initialization, even when you only have the Default constructor.
Initialization Block
Table of Contents
Copyright (c) 2008. Intertech, Inc. All Rights Reserved. This information is to be used exclusively as an
online learning aid. Any attempts to copy, reproduce, or use for training is strictly prohibited.
Courseware
Training Resources
Tutorials
Services