Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static initializer

 
Basanti Mathad
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
can anyone answer these qstns?
1. are the variables declared in the static initializer implicitly static?
2. why is it giving me the compiler error when i mention static before the variable in static initializer.
3. static
{
// static int x= 5,y=5; //gives compiler error
int x= 5,y=5;
}
static int x,y;
when i use the variables in the main program, it uses the static variable.So in this case, is the scope of the variables only within the static block?
Thank u,
basanti
 
chi Lin
Ranch Hand
Posts: 348
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1.variables declared inside static are implicitly static and you can not reference non-static menbers from the static block.
2. When the programs runs OK, If you check the vaule of the x,y, the result should be 0,0 (not 5,5).
HTH.
 
Basanti Mathad
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
am confused here....
when u say the static block members r static implicitly, then where is the question of referring the non static members?
pls explain.
thank u.
 
Dan Culache
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Basanti,
Here's my opinion:
1&2. The variables declared within a block (static or not)should adhere to the rules for local variables so the only valid modifier is final and their scope is only that block.
3. The variables declared within a block also hide (if given the same name) any local variable.

 
Dan Culache
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry, in my answer for #3 I meant:
3. The variables declared within a block also hide (if given the same name) any instance variable (I said local in my previous answer). And it's valid for static variables too, like the code shows.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic