File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes static block Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "static block" Watch "static block" New topic
Author

static block

prashant panigrahi
Greenhorn

Joined: Jan 24, 2011
Posts: 4
what is the difference between static block and method
Ben Ooms
Ranch Hand

Joined: May 16, 2011
Posts: 44

A static block is executed at class loading and a static method when its called.

See this example:


When the Bar main is executed class Foo is loaded at line 12 and produce:
static block called
when line 13 is executed static method of Foo is called and produce:
static method called


regards,
Ben
Rumesh Eranga
Ranch Hand

Joined: Jan 26, 2011
Posts: 34
Also to access a non static method you have to create an object first but not for a static method.
prashant panigrahi
Greenhorn

Joined: Jan 24, 2011
Posts: 4
thanks Ben and Rumesh
Subhash Pavuskar
Ranch Hand

Joined: Jun 29, 2011
Posts: 57

Adding to this point ,In java we have two types of methods,
1. instance methods
2static methods.
Static methods can't use any instance variables. The this keyword can't be used in a static methods. You can find it difficult to understand when to use a static method and when not to use. If you have a better understanding of the instance methods and static methods then you can know where to use instance method and static method.




Ben Ooms wrote:A static block is executed at class loading and a static method when its called.

See this example:


When the Bar main is executed class Foo is loaded at line 12 and produce:
static block called
when line 13 is executed static method of Foo is called and produce:
static method called


regards,
Ben
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40052
    
  28
Subhash Pavuskar wrote:. . . The this keyword can't be used in a static methods. . . .
Nor can the keyword super.

Nice post there
You can find it difficult to understand when to use a static method and when not to use.
Try searching for “Campbell Ritchie classification of methods” and you find this. Click the link and it will give hints about when methods might well be static.
A static method does not require use read or investigate any information about an object (of the same class). A static method does not record write alter or manipulate any information about an object (of the same class).
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: static block