Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static variable in static function

 
Thomas Whalen
Ranch Hand
Posts: 123
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why can't i put a static variable inside the main method?
 
Marilyn de Queiroz
Sheriff
Posts: 9066
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You cannot use the static modifier inside a method.
Not static variables, not static (local) inner classes, no static anything inside a method.
 
Thomas Whalen
Ranch Hand
Posts: 123
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why is this? is it because of the method's life span? what i mean is if the method is destroyed after use, but a variable local to it is declared as static then the compiler throws an error? i guess i am not getting why this matters with methods, even though i understand it from a scope point of view.
thank you marilyn.
 
Peter Simard
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Anything "static" is initialized first by the compiler. Static members are available a) class wide and B) before instantiation of an object derived from the class
Methods are inherently temporary and local in scope. Temporary because variables used in methods are destroyed as soon as the method has done it's work. Anything "static" can also be called "un-changing and available classwide".
HTH
Pete
------------------
PAS
peter@panvox.net
2b | | !2b
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic