File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes static initializers 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 initializers" Watch "static initializers" New topic

static initializers

jonas okwara
Ranch Hand

Joined: Jun 22, 2004
Posts: 58
Please could someone explain to me what static initializer is in this example:

class Test {

int a = 20;

static {
int b = 10;

Emilio Botella

Joined: Sep 06, 2004
Posts: 6
In static block you've declarated a local variable, you may use it within a loop, for example to initiate others static variables.
marc weber

Joined: Aug 31, 2004
Posts: 11343

Static variables are initialized and static block is executed at class load time, which occurs either when the first object of that class is created or when a static member of the class is accessed (even if no object is created). If an object is being created, then instance variables are initialized and non-static initializer block is executed. After this, the body of the constructor executes.

See thread:

However, as Emilio pointed out, your int b is local to the block. If you want it accessible as a class variable, then you need to declare it as static outside of that block, even if you're going to initialize it using a static block.

( Barry change static b; to static int b; )

[ September 10, 2004: Message edited by: Barry Gaunt ]

Thanks, Barry...
[ September 10, 2004: Message edited by: marc weber ]

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
I agree. Here's the link:
subject: static initializers
It's not a secret anymore!