0
static long sum(int n, long total) {
    "static" boolean exitConditionMet = false;
    if(n == 1) {
        exitConditionMet = true;
        return 1;
    } else {
        return total + sum(n-1, total);
    }
}

I need to execute different code if this variable is true. And its address should not change for all recursive calls. My code is different but I provided this as an example, please ignore the errors, it is just for understanding my problem.

You can suggest using a parameter, but I don't want that option.

Is it possible to achieve this using Java? I hope I explained it clearly.

I tried chatgpt and another answering platform. im expecting an equivalent keyword

  • 12
    "*I tried chatgpt*" — don't trust chatgpt. – Petəíŕd The Linux Wizard Sep 02 '23 at 13:46
  • 1
    This static variable doesn't do anything. – tkausl Sep 02 '23 at 13:48
  • 3
    "I tried chatgpt" - why do people do that? That mindless chatbot doesn't know how to code. All it knows is how to mash text together into something that looks plausible to a human, but there is *no* actual intelligence behind what it does. – Jesper Juhl Sep 02 '23 at 13:50
  • 4
    Static local variables are more often than not a bad idea. What is the actual problem you try to solve? Why do you think a "static" local variable would solve that problem? – Some programmer dude Sep 02 '23 at 13:50
  • @Someprogrammerdude I'm used to those in MQL4 (C++like language) coding, and now I'm solving a knapsack problem with Java, I managed to recurse correctly but now I want to fill an array that contains correct indices e.g. {5,7,8} for {11, 8,7,6,5} and sum value = 20 and I can only do that on my way back – Oleguito Swagbucks Sep 02 '23 at 13:56
  • 2
    In general just learn your "new" language from scratch. Same words like static (and even new) can have completely different meaning/behavior in different languages. – Pepijn Kramer Sep 02 '23 at 14:02
  • There are static member variables in Java classes, those work similarly. – Quimby Sep 02 '23 at 14:05

2 Answers2

0

There is no Java keyword that will allow you to declare a local variable as static. The closest in Java to that C++ would be:

class Test {
    static boolean exitConditionMet = false;

    static long sum(int n, long total) {
        if (n == 1) {
            exitConditionMet = true;
            return 1;
        } else {
            return total + sum(n-1, total);
        }
    }
}
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

Static variables in Java must be declared at the class level not inside a method.

public class StaticKeywordExample {
  private static int count = 0; // static variable  

  public static void printCount() { // static method
    System.out.println("Number of Example objects created so far: " + count);
  }
}
p1ux
  • 9
  • 3