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 How do u know when to use static? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How do u know when to use static?" Watch "How do u know when to use static?" New topic

How do u know when to use static?

Sally Curtis

Joined: Jan 10, 2004
Posts: 26
Hello, i was need to know how one would know when to make and identifier static or nonstatic?
Marilyn de Queiroz

Joined: Jul 22, 2000
Posts: 9059
If you only want one of them per class (for example, a sum), you would use a static. If you want a new one for each object, you don't want a static variable.

"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Some languages call static variables "class" variables. I like that name because they store some information about the class in general. Non-static variables store information about one particular object or instance of the class.
I had a class that for debugging needed to identify each new instance by something unique. So here's a mix of static and non static:

There is one instanceCounter variable for the class, no matter how many objects I make. And one idNumber per object so each instance gets its own id number. The numbers helped me keep messages in the console straight.
Another good use for static is to make it easier to share methods and information. If we put critical information in a particular instance of a class, we have to be able to get ahold of that instance to get the information. But if the methods or information are static, we only need to reference the classname.

This time a static variable and a static method made Logger easier to use. Classes with all static stuff are called "utility" classes. Some folks will argue that they are not "good" OO but they work and are commonly accepted.
Was that clearer or more confusing? Ask again if it's not making sense.

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
I agree. Here's the link:
subject: How do u know when to use static?
jQuery in Action, 3rd edition