wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes private static int x Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "private static int x" Watch "private static int x" New topic
Author

private static int x

mayur dhawan
Greenhorn

Joined: Sep 20, 2005
Posts: 29
Hi,
I want to know what is the benefit of using private static declaration like this.
and How are we going to use this declaration.

thanks
mayur
Antonio Tercero
Ranch Hand

Joined: Jun 05, 2008
Posts: 110
A static variable can be accessed from a static or non-static method.
Example:


SCJP 5, SCWCD 5
Taariq San
Ranch Hand

Joined: Nov 20, 2007
Posts: 192
Originally posted by mayur dhawan:
Hi,
I want to know what is the benefit of using private static declaration like this.
and How are we going to use this declaration.

thanks
mayur



One benefit might be that all instances of your class share that variable, one makes a change that all of them see.
I've modified Antonio's example to illustrate this.



1 common use is counters, say everytime a constructor is called, so you always know how many instances there are. That sort of thing.

That's just the static part, the private modifier is to restrict access to it's own class.
Antonio Tercero
Ranch Hand

Joined: Jun 05, 2008
Posts: 110
Taariq is right.
static variables and methods belong to the class, so if you want to access a static variable or call a static method from another class, you can do that(recommended):



Remember that static variables and methods are shared among all objects of the class.
Ben Zaidi
Ranch Hand

Joined: Apr 08, 2007
Posts: 151
Important benefit in additions to described above, you can access a
static variable, even if there are no instances of class created, by
simply invoking it through the class name. Static members are class
level variable rather then instance level.

Hope this helps,

Ben


Ben,
--Lost in preparation of SCJP and SCWCD--
"Start writing a new chapter, for if you live by the book you'll never make history." (Ben Sobel)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: private static int x
 
Similar Threads
Event Handling and native method
Static variable vs Static initializer
static inner class
private static Logger logger = Logger.getRootLogger();
Whacky db problem.