Hi,
freely quoting Mughal, A programmes guide to
Java Certification, p 260f.
Java allows static initializer blocks to be defined in a class. Although such blocks can include abrbitrary code, they are primarily used for initializing static variables.
(personally me (Axel, not Khalid Mughal) do not use them).
The code in a static initializer block is executed just once when the class is initialized. Note that the static initializer blocks are n o t contained in any method. A class can have more than one static initializer block. The static initializer expressions (line 3) and the static initializer blocks (line 4, line 9) are executed in the order they are specified in the class.
A static block cannot make a forward reference to static variables that are defined after its definition (if you
exchange the line 4 and 3 you get a illegal forward reference error at compile time, because variable x is not yet declared).
A typicall use of static initializer in a class is to load any external libraries that the class needs, for example, to execute native methods.
Originally posted by SteffySY Sing:
Which one statement is true about the application below?
1.class StaticStuff
2.{
3. static int x = 10;
4. static { x += 5; }
5. public static void main(String args[])
6.{
7. System.out.println("x = " + x);
8. }
9. static { x /= 5; }
10. }
Answer:
The code compiles, and execution produces the output x = 3.
My Question is how x = 3?
Thank You.