• 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

Initialization of a local variable

 
Ranch Hand
Posts: 384
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello,

Note that my question is about the syntax and not about the way to achieve something (for instance I don't want to switch to an iterative implementation). Neither do I want to add another argument to my method.

Say I have the following recursive method:



I want to set the value of the counter variable to 0 at the first invocation of that method and only then (1). Upon the second and subsequent invocations I will increment the counter (2).

Is that possible? What is the syntax I can use in order to achieve that?

Any clue welcome,

Julien.
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There's no special syntax to do that. What you can do is make two methods; the first one is what you call from the outside, the second one is the actual recursive method. Something like this:
 
Ranch Hand
Posts: 457
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
you can push these two methods into one method with varargs,

you shouldn't because it greatly reduces readability of the code
 
Sheriff
Posts: 22783
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sounds like you want the old C static method-local variables - a variable that is static within a method only.

Java doesn't have anything like this, so the only thing I know of to solve this is "upgrade" the variable to an instance (or class) variable. You initialize it with 0 when the object (or class) is initialized, then increment it when the method is called.
 
reply
    Bookmark Topic Watch Topic
  • New Topic