File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Static Initializer Code Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Static Initializer Code" Watch "Static Initializer Code" New topic
Author

Static Initializer Code

sing
Ranch Hand

Joined: Nov 29, 2001
Posts: 121
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.
Tom Stevns
Ranch Hand

Joined: Nov 20, 2001
Posts: 122
code in like static{} will be executed one time before the rest therefore
x is 10, the 15 and at last 3
regards Tom
Originally posted by SteffySY Sing:

My Question is how x = 3?

3. static int x = 10;
4. static { x += 5; }
9. static { x /= 5; }



Regards Tom Stevns, SCJP2
Axel Janssen
Ranch Hand

Joined: Jan 08, 2001
Posts: 2164
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.


sing
Ranch Hand

Joined: Nov 29, 2001
Posts: 121
Thanks Tom and Axel.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Static Initializer Code