aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes What does a static block in class mean? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "What does a static block in class mean?" Watch "What does a static block in class mean?" New topic
Author

What does a static block in class mean?

Tony Sam
Ranch Hand

Joined: Nov 19, 2001
Posts: 32
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).]


Tony Sam<BR>One want to be a SCJP...
ersin eser
Ranch Hand

Joined: Feb 22, 2001
Posts: 1072
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

Joined: Nov 19, 2001
Posts: 32
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

Joined: Nov 29, 2001
Posts: 48
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
------------------
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: What does a static block in class mean?