• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static Variable Problem

 
vijay malhotra
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
STATIC VAR. CANNOT BE DECLARED LOCAL.
 
Ravindra Mohan
Ranch Hand
Posts: 216
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
Cheers
Ravindra Mohan
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic