Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

questions about static keyword ?

 
naved momin
Ranch Hand
Posts: 692
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the output of the below code is 25 , 1
but when i write

then the output is 25 , 25
so by writing static does it maintain only one copy of counter variable , no matter how many object is being created ,
and if any new object is being created of that particular class type then it will have the latest value of counter variable , right ?
 
Alexander Kober
Ranch Hand
Posts: 32
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can consider a static field to belong to the class itself rather than to an instance. So for the sake of the argument, yes, there is only one single counter variable. Your instances will access that singleton counter, so they won't just 'have the latest value', but actually access the same thing.

Note, however, that a static counter variable is widely considered to be bad practice. It is, of course, fine to use it for debugging purposes, but a non-final public static field may introduce problems - for instance, when you're using multiple threads in your application (two threads accessing the same variable may lead to inconsistencies which are incredibly hard to debug).
 
naved momin
Ranch Hand
Posts: 692
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Alexander Kober wrote:You can consider a static field to belong to the class itself rather than to an instance. So for the sake of the argument, yes, there is only one single counter variable. Your instances will access that singleton counter, so they won't just 'have the latest value', but actually access the same thing.

Note, however, that a static counter variable is widely considered to be bad practice. It is, of course, fine to use it for debugging purposes, but a non-final public static field may introduce problems - for instance, when you're using multiple threads in your application (two threads accessing the same variable may lead to inconsistencies which are incredibly hard to debug).

thanks
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic