File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Static Variable Problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Static Variable Problem" Watch "Static Variable Problem" New topic

Static Variable Problem

vijay malhotra

Joined: Nov 26, 2000
Posts: 26
Why in a static method for ex main() method we cannot
declare static variable ?
public static void main(String args[])
static int i;
ratul banji
Ranch Hand

Joined: Mar 15, 2001
Posts: 108
Ravindra Mohan
Ranch Hand

Joined: Mar 16, 2001
Posts: 216
Hi Vijay,
The reason for static variable not allowed to be declared locally is on the fact that static variables are "class" variables so they are accessible to all the instances of the class. Now let
us consider a scenario where you have a method that declares a static variables (i.e., the scope of this variable would be local as it is declared locally this contradicts the basic purpose of defining a variable as static) , an object calls this method does same manupulation and when the method call is returns the static variable must die as it is now of scope, else we are in more serious trouble as this hanging static variable may conflict/temper with other variable.
I guess this serves the purpose of this discussion.
Ravindra Mohan
jQuery in Action, 3rd edition
subject: Static Variable Problem
It's not a secret anymore!