aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Forward Referencing 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 "Forward Referencing" Watch "Forward Referencing" New topic
Author

Forward Referencing

Satish Kota
Ranch Hand

Joined: Feb 08, 2006
Posts: 88
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?



SCJP 5.0 77%
Rancy Chadha
Ranch Hand

Joined: Jul 12, 2006
Posts: 135
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


Thanks,<br />-Rancy
raja kanak
Ranch Hand

Joined: Oct 18, 2006
Posts: 135
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


live
hardikjava shah
Greenhorn

Joined: Dec 12, 2005
Posts: 13
static code runs in the order in which they appear in the code.
Satish Kota
Ranch Hand

Joined: Feb 08, 2006
Posts: 88
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?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Forward Referencing