Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static Variables

 
summer_gsr
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Ajith Kallambella
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
AFAIK, you cannot declare static variables in the method scope. They can only appear in the class scope. That's the rule!
Ajith
 
summer_gsr
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3141
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
summer_gsr
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic