I know a little about initialization blocks that are used in classes. But i came across this question:
//What is the output of the following program?
public class Test {
private static int i = 0;
private static int j = 0;
public static void main(String[] args) {
int i = 2;
int k = 3;
// What is this thing, that appears to be like an initializer block inside the main method?
{
int j = 3;
System.out.println("i + j is " + i + j);
}
k = i + j;
System.out.println("k is " + k);
System.out.println("j is " + j);
}
}
My question is: What is this thing, that appears to be like an initializer block inside the main method?
[This answer is addressed to a wider novice audience]
Within a method, a set of declarations and statements enclosed with { } braces is a compound statement, also called a block statement or simply a block. It creates a new scope nested within the current scope within a method body.
This is used all of the time in constructs that require more than one statement to be executed as a unit. E.g.:
if (a > b)
{ // Block
int tmp = a; // 'tmp' is local to this block
a = b;
b = tmp;
}
The block syntax may appear unusual, however, when used by itself without a controlling statement:
// Bare block with no controlling if/else/for/while/do/switch
{
int t = frob(b);
b = frob(a);
a = flub(t, a);
}
This kind of thing is typically done to isolate a complicated chunk of code within its own scope, especially if it uses a lot of local variables that are not needed anywhere else within the parent method.
This syntax can be over-used, of course:
void froodle(int a, int b)
{{
if (a < 0 || a < b)
{{
frob(-a, b);
frob(b, 0);
}}
}}
While the {{ }} double braces look unusual, they simply define a block nested within another block. In code above, the entire method body contains a single statement, which is itself a block. For clarity, this can be rewritten as:
void froodle(int a, int b)
{
{
if (a < 0 || a < b)
{
{
frob(-a, b);
frob(b, 0);
}
}
}
}
The block syntax is a special case when it appears within a class definition but not within a method body. In these cases, it is a class initializer, i.e., a block of code that is executed when the class is first loaded and initialized. It is as if the block is the body of a special unnamed function that gets executed at class loading time.
class Bar
{
static Foo myFoo;
// Class initializer
static
{
myFoo = new Foo(100);
myFoo.freeble(200);
}
...
}
Addendum
Note that the class initialization block requires a static keyword preceding it (which I added to the example code above). Note also that the code can only access static members and methods in the class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With