aspose file tools*
The moose likes Java in General and the fly likes questions  about static keyword ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "questions  about static keyword ?" Watch "questions  about static keyword ?" New topic
Author

questions about static keyword ?

naved momin
Ranch Hand

Joined: Jul 03, 2011
Posts: 692

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 ?


The Only way to learn is ...........do!
Visit my blog http://inaved-momin.blogspot.com/
Alexander Kober
Ranch Hand

Joined: Aug 05, 2011
Posts: 32

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

Joined: Jul 03, 2011
Posts: 692

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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: questions about static keyword ?