Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
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 REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Static Variables" Watch "Static Variables" New topic

Static Variables


Joined: Jan 12, 2001
Posts: 7
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.

Ajith Kallambella

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!

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

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,
Jane Griscti
Ranch Hand

Joined: Aug 30, 2000
Posts: 3141
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 Griscti
SCJP, Co-author Mike Meyers' Java 2 Certification Passport

Joined: Jan 12, 2001
Posts: 7
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.
I agree. Here's the link:
subject: Static Variables
It's not a secret anymore!