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


manoj kumar jena

Joined: Sep 24, 2007
Posts: 25
what is the difference between static block and static method?
which one is better?
please explain it with a piece of code.
Matthew Plant

Joined: May 07, 2008
Posts: 18
What do you mean by static block?

Do you mean a static initialiser? eg.

static {
// Do something.
// Do something else.

If so, this is like a contructor but is called when the class is loaded rather then when the object is contructed.

If I have misunderstood, I apologise.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15081

Originally posted by manoj kumar jena:
which one is better?

They are different things with different purposes, so asking which is better is a meaningless question.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Matthew Plant

Joined: May 07, 2008
Posts: 18
You would use a static initialiser to set up static variables before you access them via your static methods.
Ilja Preuss

Joined: Jul 11, 2001
Posts: 14112
It's a bit like asking "what is the difference between a hammer and a hammerhead shark? Which one is better?"

The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46334
And welcome to JavaRanch, Manoj.
John M Morrison

Joined: Jul 25, 2005
Posts: 21
To fully understand this, let's look at the sequence of events. Consider the following simple class.

Now suppose we are in another class. Supppse this line

is the first instance of a Minter object that is declared. At that time, the Java class loader will load the code for the Minter class. First, all of the static stuff is seen to. In an area of memory shared by all instances of the class, go the static instance variables and methods. This includes the constructors. The static block is executed. All this occurs before the birth of the dirst object.

Next, the first instance of the Minter class is created. It gets assigned the first ID. Each new instance of a Minter gets an ID one higher than its predecessor.

I hope this simple example helps.

I agree. Here's the link:
subject: Static
It's not a secret anymore!