Instance variables belong to an instance of the class. Static variables belong to the class itself, and may be used without instantiating the class.
You should use static members when you need functionality without creating an instance. An example where a lot of people use static members is when defining constants (like Math.PI) or utility methods (like StringUtils.isBlank()). Whether or not static methods are a good idea or not is debatable, at least in my opinion.
David is spot on.Another easy example would be think you have a class Call Egg .So you can create Egg objects using that class .Now you might be having several instance variables which describes a particular egg like eggColor .eggSize . So these are instance variables .Value of those variables are unique to that particular object .And You cannot have a eggColor unless you already got an Egg Object.So remember you can never use instance variables without creating a actual object.
Now you also want to keep track of how many eggs do you have in your System. So this howManyEggs variable is not unique to each and every egg object.It is a common attribute to all the eggs .
If you ask from egg1 :Hey What is your color ? He might say I'm white
If you ask from egg2: Hey what is your color ? He might say I'm yellow
But if you ask How many eggs are in the system by them both should give the same answer.So noOfEggs is a attribute represents the class Egg.So use a class member(attribute) to represent it.
Hope this will Help!
[Bsc in Computer Science and Engineering] [SCJP 80%][BCS certificate level]
lakmal .right on the top, egg represent object ( instance of a class ) ..if you want to know....how many objects(eggs) of that class type are created ... opt for static variable... since it is unique for a class (class level) ... and if you want to have a global variable kind mention use' public static 'keyword(behaves globally ...but not global).....
subject: difference between an instance variable and static variable?