-7

I tried using such a variable but it gave me an error which was surprising for me. Looking around for an answer as it makes no sense to me. Wanted to know if there was some security reason or something behind it....

  • 1
    Why would you need static local variable? What do you mean by that? Show me your code – Antoniossss Dec 14 '17 at 14:02
  • I'm pretty sure that would defeat the purpose of `static`. – achAmháin Dec 14 '17 at 14:02
  • What did you tried and what error did you receive? Please provide a MCVE. [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) –  Dec 14 '17 at 14:03
  • It is simply a bad code style. But you may use static members. Static members can be initialized by the static {} function. But static variables can't - or might need some crazy syntax and much special effort. Or use just a member - which is almost the best way. – brummfondel Dec 14 '17 at 14:04
  • 2
    @devpuh - I'm not sure we need an MCVE to be able to tell the OP that static locals don't exist. – Oliver Charlesworth Dec 14 '17 at 14:05
  • 4
    C and C++ have functions outside of classes. Java does not. Anything you could do with a static local variable in C/C++, you can do with a static class variable in Java. – Andy Thomas Dec 14 '17 at 14:05
  • @OliverCharlesworth yes a static local variable can't exist in java, but it's possible that the asker means something else. –  Dec 14 '17 at 14:07

3 Answers3

0

Any variable declared within a method is supposed to be local to the method .It gets stored in the method stack in the JVM, which is one per thread . When you use static keyword, it indicates that this variable will be common for all object of the class

Vishnu T S
  • 3,476
  • 2
  • 23
  • 39
0

By rule, when the static variable scope (or visible) is for the whole class, by common sense, how a local variable be declared static. A local variable scope is within the method where it is declared. If the local variable is declared static, the meaning of static is lost. If the local variable is static, the purpose of static variable is bypassed. For this reason, compiler does not allow static local variables.

Source

achAmháin
  • 4,176
  • 4
  • 17
  • 40
0

Static variables are instantiated at the start of program execution.

Local variables are instantiated when line of code inside the method that creates the variable is executed, and only last for the duration of method execution.

The keyword static inside of a method declaration violates the local scope and therefore is not allowed.

C Henry
  • 148
  • 12