File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Static Variables 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 "Static Variables" Watch "Static Variables" New topic
Author

Static Variables

summer_gsr
Greenhorn

Joined: Jan 12, 2001
Posts: 7
Hi,
Iam learning java and I confused with the concept of static modifier. I was hoping if anyone can clarify my doubt.
class StaticTest
{
static int y;
int x;
static void method()
{
static int a=10;
int b=30;
System.out.println("a "+a+"b "+b);
System.out.println("y "+y+"x "+x);
}
This is giving me a compilation error because I defined a static variable in a static method. Why cann't I declare a static variable in a static method.
Summer


GSR
Ajith Kallambella
Sheriff

Joined: Mar 17, 2000
Posts: 5782
AFAIK, you cannot declare static variables in the method scope. They can only appear in the class scope. That's the rule!
Ajith


Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA).
summer_gsr
Greenhorn

Joined: Jan 12, 2001
Posts: 7
Ajith, Iam a beginner and Iam kind of confused here. Can you please explain the actual reason why I cann't declare static variables in methods. I understand that it is a rule but why?
Thank You,
Summer
Jane Griscti
Ranch Hand

Joined: Aug 30, 2000
Posts: 3141
Summer,
static variables and methods are class members. Only one copy exists for the entire class.
In your example <code>static void method()</code> only one copy of the method and all it's variable exists; so declaring a static variable in the method would be redundant.
Hope that helps.
Jane


Jane Griscti
SCJP, Co-author Mike Meyers' Java 2 Certification Passport
summer_gsr
Greenhorn

Joined: Jan 12, 2001
Posts: 7
Jane,
Thank you, Iam now clear why they shouldn't be declared in a method it is because static variables and methods are class members and declaring them in method is just further restricting them and so they will be a complilation problem.
Thanks,
Summer
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Static Variables
 
Similar Threads
Increment operator
how the program works?
Static Modifier
Dan's questions : static variable
Int By Reference passing..