• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

write operation before declaration...

 
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi everyone,

please help me to clear the following doubt.

1>what is the rule to use a variable(read or write) before declaration.

2> code snippet:
class MyClass{

static{
int x = 2 * var1; //line1
int y = 3 * MyClass.var1; //line2
}

static{
int var1 = 10;
}

In the above code line1 gives error but line2 runs successfully.I am not able to understand the behaviour. Please explain how this code is working.

How the compiler(or system) handles or process var1 in line2 which is running nicely without declaring var1 before using it at line2.

I hope i am very much clear what i am trying to ask....if not please reply back..
Thanks in advance
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Both line 1 and line 2 fail to compile with Java 6.0. Are sure you typed in your program correctly? Also, please tell us the compiler version you are using to compile your program.

All your variables are local variables, they only exist in their respective static initializer blocks.
[ January 28, 2007: Message edited by: Barry Gaunt ]
 
Ranch Hand
Posts: 218
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

what is the rule to use a variable(read or write) before declaration



Perhaps you mean the forward-declaration rules...


Restrictions on the use of Fields during Initialization

The declaration of a member needs to appear textually 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:
� The usage occurs in an instance (respectively static) variable initializer of C or in an instance (respectively static) initializer of C.
� The usage is not on the left hand side of an assignment.
� The usage is via a simple name.
� C is the innermost class or interface enclosing the usage.
A compile-time error occurs if any of the four requirements above are not
met.

 
reply
    Bookmark Topic Watch Topic
  • New Topic