0

I was searching for what static variable mean I find this site

http://java-questions.com/keywords-interview-questions.html

and its his declaration about static variable when I use his example I find different result

Static keyword can be used with the variables and methods but not with the class. Anything declared as static is related to class and not objects.

Static variable : Multiples objects of a class shares the same instance of a static variable.Consider the example:

public class Counter{
 private static int count=0;
 private int nonStaticcount=0;
 public void incrementCounter(){
   count++;
   nonStaticcount++;
 }
 public int getCount(){
  return count;
 }
 public int getNonStaticcount(){
  return nonStaticcount;
 }

 public static void main(String args[]){

   Counter countObj1 = new Counter(); 
   Counter countObj2 = new Counter();
   countObj1.incrementCounter();
   countObj1.incrementCounter();
   System.out.println("Static count for Obj1: "+countObj1.getCount());
   System.out.println("NonStatic count for Obj1: "+countObj1.getNonStaticcount());
   System.out.println("Static count for Obj2: "+countObj2.getCount())
   System.out.println("NonStatic count for Obj2: "+countObj2.getNonStaticcount())
 }

Output

Static count for Obj1: 2
NonStatic count for Obj1: 1
Static count for Obj2: 2
NonStatic count for Obj2 :1

when I use this Example I got

 Static count for Obj1: 2  
    NonStatic count for Obj1: 2 // instead of 1
    Static count for Obj2: 2
    NonStatic count for Obj2 :0 // instead of 1

Can any one tell me what static variable mean and Example declare how can I use it in my method

thank you

Mina Fawzy
  • 20,852
  • 17
  • 133
  • 156

2 Answers2

3

You get the wrong result because you are incrementing countObj1 twice :

Counter countObj1 = new Counter(); 
Counter countObj2 = new Counter();
countObj1.incrementCounter();
countObj1.incrementCounter();
//     !!!

Replace it with :

Counter countObj1 = new Counter(); 
Counter countObj2 = new Counter();
countObj1.incrementCounter();
countObj2.incrementCounter();

Now, you have the right result :

Static count for Obj1: 2    //Counter.count
NonStatic count for Obj1: 1 //obj1.nonStaticcount
Static count for Obj2: 2    //Counter.count (the same as in the first line)
NonStatic count for Obj2 :1 //obj2.nonStaticcount
Arnaud Denoyelle
  • 29,980
  • 16
  • 92
  • 148
1

You're invoking incrementCounter() twice on the same object :

   countObj1.incrementCounter();
   countObj1.incrementCounter();

Instead you should do:

   countObj1.incrementCounter();
   countObj2.incrementCounter();
Evdzhan Mustafa
  • 3,645
  • 1
  • 24
  • 40