21

In C/C++ we use static local variables for maintaining a method's state. But why it is not supported in Java?

Yes, I can use an static field for this purpose. But isn't it a bit weird to create a field for maintaining only one method's state?

Rafi Kamal
  • 4,522
  • 8
  • 36
  • 50
  • what's your use case? In general it makes sense for static data to be part of object state. – TJD Sep 05 '12 at 04:16
  • @Richard - yea, it is not weird ... just different. – Stephen C Sep 05 '12 at 04:23
  • 3
    @Rafi - asking "why" questions about the design of existing languages is generally a pointless exercise ... unless you intend to design and implement a new language. The Java language behaves the way it does, and you need to adapt your use accordingly ... or use a different language. – Stephen C Sep 05 '12 at 04:26
  • @StephenC I just wanted to know if there is any advantage for not allowing this in Java.. – Rafi Kamal Sep 05 '12 at 04:29
  • @Rafi - 1) what difference would it make? Are you planning to design a new programming language? 2) Do you think anyone reading this Question was in the room when the decisions were made? 3) Isn't the reason - simplicity - obvious anyway? – Stephen C Sep 05 '12 at 04:32
  • 5
    Asking why is also a great way to figure out whether you're missing a great replacement for the functionality that you have in mind, or at least a feature you might not have know about or understood completely. – GargantuChet Sep 05 '12 at 06:29
  • 11
    I'd rather a language newcomer ask a great "why" question and have a shot at learning a new trick, than to be silently irritated and learn nothing. And by asking on Stack Overflow, good answers will make into the Google results for the benefit of anyone who wonders the same thing a week from now. – GargantuChet Sep 05 '12 at 06:37
  • I think the underlying decision here is that methods aren't first class objects. That and the need for garbage collection together meant that you simply can't have method-scoped variables. An object has a life cycle, a method doesn't. So how do you garbage collect things referenced by a method? Of course you can declare a method life cycle to be tied to its declaring object's, but that would also mean that its state would be tied to the object state. And from there it's a small step to ditch the idea completely. – biziclop Apr 14 '15 at 14:40

5 Answers5

34

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.

Tony K.
  • 5,535
  • 23
  • 27
5

The Java language spec doesn't seem to defend the omission of variables that correspond to C static variables.

Hiding state in class methods has a few drawbacks when seen from a Java perspective. Generally the existence of a function-level static variable isn't the sort of implementation detail that you'd want to expose outside of that function.

But the method's state is actually part of the class's state, and method-level static variables would have to be serialized / deserialized any time the object is persisted. This might not sound common, coming from a C background, so I'll note a few common examples.

  • Application server clusters can pass user session objects between nodes in order to provide fault tolerance.
  • JAXB could be used to marshall an object into an XML document
  • JPA can be used to persist object state to a database

If the variable's value is worth saving when the object is persisted, then there's a good chance that code outside of that class will need to reference that value. And suddenly that means defining access levels -- is a static variable in a public method automatically public? Or would a programmer have to declare it so?

We also have to think about extensibility. Would derived classes be required to implement the same static variable? Or would there be a reference to the variable from the function in the base class?

It's more likely that the C method that would use a static local variable would be a good candidate for a class in Java. It has state and hopefully exists for a single purpose. There's little drawback to encapsulating the functionality into an object, and it makes for a cleaner separation between transient values (such as local variables) and more long-term state.

GargantuChet
  • 5,691
  • 1
  • 30
  • 41
1

Some of the other answers show why you might not want to have this. But you can also ask why from a historical perspective.

To answer this you have to start to see why C does have static local variables. C has much fewer means than Java and C++ to limit the scope of a variable, the only options for static data are 'inside the file' and 'everywhere'. So this provides an extra layer, to limit the scope.

An important aspect of C++ is compatibility with, so it is allowed in C++ as well. But it doesn't need local static scope as much anymore, because there are many other means to limit scope of static data. The use is not popular in (modern) C++.

Java merely takes a lot of inspiration from C/C++, it didn't have to worry about backwards compatibility, so it could be left out.

Thirler
  • 20,239
  • 14
  • 63
  • 92
0

Perhaps because methods are not objects in Java; so maintaining their state as you said make not much sense and I guess you'd have to create a new concept in the byte code for that; use an object as Tony K. said.

Cameron Skinner
  • 51,692
  • 2
  • 65
  • 86
Marc Polizzi
  • 9,275
  • 3
  • 36
  • 61
-2

instance methods are invoked by the instance(objects) of the class . Static things belongs to the class not to the object that's why local variables are not static.Instance variables are static and they can also initialized at the time of class loading by static blocks. enter image description here

for more information please visit :- https://www.youtube.com/watch?v=GGay1K5-Kcs&t=119s