Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Forward Referencing

 
Satish Kota
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following code gives forward reference error



But when i replace System.out.println(x); in static block to assignment operation like x=33. The programe compiles fine.



Why isnt forward referencing error getting applicable when we are assigning value to static variables?

 
Rancy Chadha
Ranch Hand
Posts: 135
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Satish,

public class Test
{
static{
System.out.println(x);
}
static int x=23;

public static void main(String[] args) { }
}

The reason why this code gives you forward referencing error is because here you are trying to print value of x. Which is violating the rule of declaration before read.
For forward referencing to work you can using the variable as the destination but not as a source. What I mean is:

int y=0;
y = x = 5; //This expression evaluates as (y = (x = 5))
int x;
Above code will work fine because here x is used on left hand side as source for inner expression.
Where as same code will give error if you do

int y=0;
y=x; // x is used as source
int x;
In your code you were using x as source so you were getting the error.
I hope this clears the point.

Thanks,
Rancy
 
raja kanak
Ranch Hand
Posts: 135
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Satish Kota:
The following code gives forward reference error



But when i replace System.out.println(x); in static block to assignment operation like x=33. The programe compiles fine.



Why isnt forward referencing error getting applicable when we are assigning value to static variables?



which one will run first
static block or static declaration/initialization
 
hardikjava shah
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
static code runs in the order in which they appear in the code.
 
Satish Kota
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Rancy Chadha:
For forward referencing to work you can using the variable as the destination but not as a source


I think that rule applies only to static block. In case of instance block i am able to forward reference a variable x using this pointer. As shown :



Any comments?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic