Do you know code block? Of course you know! Block of code defines the scope of variables and puts more statemets together. But what about non-static blocks as a class member? You can put them as other class members such as static blocks, class variables and methods.
E.g. static block is executed after class is loaded. This example is clasic block of code...
{
// block of statements: Fibonacci series
int s, f1 = 0, f2 = 1;
while (f1 < 100) {
System.out.println(f1);
s = (f1 + f2);
f1 = f2;
f2 = s;
}
}
And now, try to find non-static block inside BlockTest class...
public class BlockTest {
// field without explicit initialization
private int id;
// field with ininitialization
private String value = "UNDEF";
static {
System.out.println("static code: executed onece when the class is loaded\n");
}
{
System.out.println(debug("executed before constructor, but after members initialization"));
}
// constructor
public BlockTest(int id, String value) {
this.id = id;
this.value = value;
System.out.println(this.debug("constructor"));
}
String debug(String msg) {
return String.format("%d - %5s: %s", this.id, this.value, msg);
}
// main method
public static void main(String[] args) {
new BlockTest(1, "one");
new BlockTest(2, "two");
new BlockTest(3, "three");
}
}