• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Why cannot declare static var in methods ?

 
Ranch Hand
Posts: 156
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class A {
public static void static_m1 () {
//static String static_s=""; //illegal
}
public void m1 () {
//static String static_s=""; //illegal
}
public static void main (String [] args) {
}
}
Can anybody explain to me (in detail if possible) why you cannot declare static variables in methods ?
Thanks !!!
 
Author & Gold Digger
Posts: 7617
6
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Static variables, i.e. class variables, pertain to the class as a whole. Non-static variables, i.e. instance variables, pertain to an object.
Moreover, static variables can be used within static and non-static methods. Non-static variables can be used only in non-static methods. What would be the point of declaring static local variables within methods?
 
Ranch Hand
Posts: 115
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Static local variables are allowed in C/C++. People who learned these languages first may expect Java to work the same way. Java is similar to C++, but is not a super-set of C++.
Here's an explanation of local static variables in C, NOT Java
There's only one instance, which lives in fixed memory (not the stack or heap). It behaves like any other static variable, which is to say its value/state are remembered across multiple invocations of the enclosing function.
 
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Just a thought:
Declaring a local variable static, private, public or protected would imply that the local variable is accessible from outside the method. This is not possible for local variables because they are placed in the stack frame for the method. The stack frame is destroyed when the methods ends.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic