Hi all,

I learned that "local static variable" with in a function is not allowed in JAVA as in C++.

I guess it violates the rule of "static" as it's should not depend on objects but is there any alternative way avaiable to accomplish that ? (i.e scope is restricted to fuction but lilfetime untill the program ends)

Is any other reason why "local static variables" is not allowed ?

Thanks in advance.

Recommended Answers

All 3 Replies

There is no need for a mthod to retain it's own state separate from it's instance context. If you need to maintain state in an object, make it a class level variable. If you really feel that the method MUST retain it's own separate state then you probably have a case for a separate class instead of a method.

Static is just that, by definition it's shared between all instances of a class.

A method can have final variables, which may be what you're looking for. These are however rarely used, mainly to preserve variables which are of interest to method local anonymous inner classes.
Personally in a decade of programming in Java I've rarely if ever encountered them.

Yes, now I understood why there is no such thing in JAVA .Thanks to Ezzaral and jwenting .

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.