wood burning stoves
The moose likes Beginning Java and the fly likes Static Initializer Block Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Static Initializer Block" Watch "Static Initializer Block" New topic

Static Initializer Block

Sherry Jacob
Ranch Hand

Joined: Jun 29, 2005
Posts: 128
I was going thru Static Initializer Block topic in the Khalid Mughal book.
The book mentions a small example 2 depict illegal forward referencing.

The theory states that there is an illegal forward referencing at (4) where an attempt is made to read the value of field sf1 before it is declared ?

Howz that so ? It's been declared at (1).

<strong><br />Cheers !!<br /> <br />Sherry<br /></strong><br />[SCJP 1.4]
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

Line 1 is not a declaration, which would look like

int sf1 = 20;

It's an assignment. And of course, variables declared inside a static initializer block -- or any block -- are local to that block; so if line 1 were a declaration, then this discussion of static variable initialization would be irrelevant.

[Jess in Action][AskingGoodQuestions]
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
As EFH points out, there is something missing in your post. You should look for something like

private static int sf1;

further down in the code listing. This is the declaration NOT line (1).

As a review, all variable declarations must contain the type of the variable. Instance variables also contain an optional access modifier (private, protected, or public) and an optional "final" specifier. Class variable declarations also contain the keyword "static". Declarations can also contain an = and a value to initialize the variable. However, without the type specifier, an = alone is just an assignment operation not a declaration.

I apologize for babbling on. I hope this clarifies the differences between declaration, initialization, and assignment. If not, please post your concerns or review your textbook for futher information.


Java API Documentation
The Java Tutorial
I agree. Here's the link: http://aspose.com/file-tools
subject: Static Initializer Block
It's not a secret anymore!