This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • 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