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

static

Arun Prasath
Ranch Hand

Joined: Jul 18, 2006
Posts: 60
The following snippet is executed well...
static
{
i=10;
}
static int i;

But, this code errors saying "illegal forward referencing"..,Why...?

static
{
i=10;
System.out.println(x);
}
static int i;

When an instance variable in the first snippet is referenced(used) well,..
Why cannot it use the same when printing in the second snippet?
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Actually, the second one would complain about "unknown symbol x". Perhaps you'd like to restate your question more clearly?


[Jess in Action][AskingGoodQuestions]
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3645
    
  15
Replace the x with i and you do get the error the OP mentioned.


Joanne
Chris Everty
Greenhorn

Joined: Aug 02, 2006
Posts: 7
Hi Arun,

you need to place the declaration of i before the static block like:

If you try to do it the other way around, the compiler will moan, as it does not know about i.
Chetan Raju
Ranch Hand

Joined: Aug 02, 2006
Posts: 109
Java follows the declaration before read rule. In the first case, you are trying to assing a value to a variable. In this case, the variable is to the left side of = whereas in the second case you are trying to read the variable before declaration ie., variable on the right hand side of =. This is not acceptable in java.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: static