Why there is no local static variable in Java?

You have found the only solution.

Java dropped a number of complexities from C++, and this was one of them.

Static variables scoped to a function do nasty things to you in concurrency (e.g. strtok is a famously nasty one to use with pthreads, for exactly this reason).

In general, what you want is an object with state. The function in question should then have an object-level variable. Then you can create instances that each maintain state.

Much easier to understand/maintain/etc.

If you truly need to maintain state as a singleton, then static fields are it.

Leave a Comment