Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static

 
Arun Prasath
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually, the second one would complain about "unknown symbol x". Perhaps you'd like to restate your question more clearly?
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Replace the x with i and you do get the error the OP mentioned.
 
Chris Everty
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic