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

What does a static block in class mean?

 
Tony Sam
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • 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).]
 
ersin eser
Ranch Hand
Posts: 1072
  • Mark post as helpful
  • send pies
  • 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
  • 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 ??

 
Thomas Bigbee
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • 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
------------------
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic