GeekInterview.com
   Home |  Tech FAQ  |   Interview Questions |  Placement Papers |  Tech Articles |  Learn |  Freelance Projects |  Online Testing |  Geeks Talk |  Job Postings |  Knowledge Base | Site Search |  Add/Ask Question

  GeekInterview.com  >  Interview Questions  >  J2EE  >  Core Java

 Print  |  
Question:  static data member

Answer: what is the use of static data member?


July 07, 2008 22:52:08 #1
 r.praveenkumar CRM Expert  Member Since: October 2007    Total Comments: 21 

RE: static data member
 
consider a situation where we would like to count the no of objects created for a particular class. let us consider a program

class ex
{
public int count;
public ex()
{
count=count+1;
}
public static void main(String as[])
{
ex o1,o2;
System.out.println(o1.count);
System.out.println(o2.count);
}
}
the output is
1
2

in the first line see 1 is the output though 2 objects are created this is because
o1.count is different from o2.count these two counts are totally different from each other so to maintain a data member which is common to all the objects we go for static data member.

now consider the following program which counts exactly the no of objects created.

class ex
{
public static int count;
public ex()
{
count=count+1;
}
public static void main(String as[])
{
ex o1,o2;
System.out.println(o1.count);
System.out.println(o2.count);
}
}
the output is
2
2

see now we got the correct output here the static count is common to all the objects if we change the value in one it will automatically reflect in all objects.
     

 

Back To Question