Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static

 
manoj kumar jena
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is the difference between static block and static method?
which one is better?
please explain it with a piece of code.
 
Matthew Plant
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 15214
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Matthew Plant
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You would use a static initialiser to set up static variables before you access them via your static methods.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's a bit like asking "what is the difference between a hammer and a hammerhead shark? Which one is better?"
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And welcome to JavaRanch, Manoj.
 
John M Morrison
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

JMM
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic