This week's book giveaway is in the General Computing forum. We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line! See this thread for details.
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
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
posted
0
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
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, 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