• 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

What does a static block in class mean?

 
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi all,
i usually see some code in a class simply like this:
class A{
int i;
static{
int i=1;
void amethod(){
}
// more variables and methods may added there
}
public static void main(String[] args){
//code omitted there
}
}
i just know that the static block always executes before the main method, i am wondering that what's the use of the static block , i don't know why !!
Needing your help...
[This message has been edited by Tony Sam (edited December 10, 2001).]
 
Ranch Hand
Posts: 1072
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
you can not declare a method within a static block.
static block gets executed at the class load time...
read RHE page 91.
 
Tony Sam
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by ersin eser:
you can not declare a method within a static block.
static block gets executed at the class load time...
read RHE page 91.


Ya,i made a mistake ,there wont be any method in it ,but i really want to know what's the use of this , is this just perform welcome message ??

 
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
static blocks belong to the class, they are usually used for initialization purposes - static blocks can only access static (class) variables. The reason they are used is that you can do more in a block than you can do in an initialization statement.
Hope that helps, Tom
------------------
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic