File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes use a variable before it's declaration 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 "use a variable before it Watch "use a variable before it New topic

use a variable before it's declaration

westwindode west

Joined: Dec 15, 2002
Posts: 17
Hi, everybody.
This following content and a piece of code are from sun website:
It's about the "Restrictions on the use of Fields during Initialization". It also says :"The declaration of a member needs to appear before it is used only if the member is an instance (respectively static) field of a class or interface C and all of the following conditions hold."
If a variable is used before it's declaration, but the variable is on the left side of an assignment (like line 3 of the code), according to the book, it will compile and run well. But when i compile it, java1.4 JDK reports:
( illegal forward reference
x = 100
Did the book make a mistake or it's b/c the book was with different version of java?
class UseBeforeDeclaration {
static {
x = 100; // ok - assignment
int y = x + 1;
// error - read before declaration
... some lines of codes
static int x;
Thanks a lot...
Valentin Crettaz
Gold Digger

Joined: Aug 26, 2001
Posts: 7610
Please check out the following discussion which handles the same topic:
regarding forward referencing and 'implicit narrowing conversion

[Blog] [Blogroll] [My Reviews] My Linked In
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
No, I think this code is a bit different from the situation discussed in the link. This code still does not compile under 1.4.1, and that is correct according to a literal interpretation of the JLS here. The key is to realize that

is a use of x which is not on the left hand side, and this occurs before the declaration of x. It doesn't matter if there was another, previous line

Even though common sense tells us that this line has made a definite assignment to x and so subsequent code should be able to use x, the JLS rules cited here make no mention of the effect. So forget common sense - "int y = x + 1;" is a use before declaration, according to the JLS.

"I'm not back." - Bill Harding, Twister
westwindode west

Joined: Dec 15, 2002
Posts: 17
Thank you both...
I'll try version 1.4.1 tonight (rather than 1.4.0), and I suppose the line x = 100 might work then...
meanwhile, i now understand why int y = x + 1 would not compile...
It's a nice experience to find clarity in the middle of confusion
westwindode west

Joined: Dec 15, 2002
Posts: 17
by j2sdk1.4.1_01 the line i = 100 does works...

I agree. Here's the link:
subject: use a variable before it's declaration
It's not a secret anymore!