Think of a for loop as a little anonymous function that takes the loop index value as a parameter. In order to start the next iteration of the loop, the function can return a call to itself with a new value for the loop index parameter.

Like this:

Object loop(int i, Object data) {
    if (i > 0) {
        return loop(i - 1, evolve(data));
    } else {
        return data;
    }
}

That's the same as this:

for ( ; i > 0; i--) {
    data = evolve(data);
}

In some languages, particularly Scheme, and who knows maybe Java 8 or 9, the compiler is guaranteed to compile a recursive function such as the function loop above just the same as it compiles the for loop above.

In other languages, including the current and past versions of Java, nearly all compilers will make an executable that builds a big call stack. When the call stack is large it may even overflow the permitted size and crash the program.

Answer from minopret on Stack Overflow
Top answer
1 of 2
2

Think of a for loop as a little anonymous function that takes the loop index value as a parameter. In order to start the next iteration of the loop, the function can return a call to itself with a new value for the loop index parameter.

Like this:

Object loop(int i, Object data) {
    if (i > 0) {
        return loop(i - 1, evolve(data));
    } else {
        return data;
    }
}

That's the same as this:

for ( ; i > 0; i--) {
    data = evolve(data);
}

In some languages, particularly Scheme, and who knows maybe Java 8 or 9, the compiler is guaranteed to compile a recursive function such as the function loop above just the same as it compiles the for loop above.

In other languages, including the current and past versions of Java, nearly all compilers will make an executable that builds a big call stack. When the call stack is large it may even overflow the permitted size and crash the program.

2 of 2
2

Haters aside, let's do this! [1]

Given:

int x = 3;
for (int i = 0; i < x; i++) {
  for (int j = 0; j < x; j++) {
    for (int k = 0; k < x; k++){
      list.add(array[i] + array[j] + array[k]);
    }
  }
}

Let's consider that each loop is it's own recursive function - as this makes the recurrence cases much easier! This is also the only "non-thinking" method I know of to turn the loops into recursion. The recursive depth will be limited to 3*x => i+j+k so it's "fairly safe" for a smallish[2] x.

In Java it requires a separate method for each loop to encode this structure. (In a language with higher-order functions these three functions might be abstractly combined .. but not in Java [7].)

void loopI(int i) {
    if (i < x) {
      loopJ(0);   // "start j loop"
      loopI(i++); // "next i loop" / recurrence case
    }
    // "end loop" / base case
}

void loopJ(int j) {
    if (j < x) {
      loopK(0);
      loopJ(j++);
    }
}

void loopK(int k) {
   if (k < x) {
     list.add(array[i] + array[j] + array[k]);
     loopK(k++);
   }
}

// do it!
loopI(0); 

All of these could be combined into a single recursive function, but that makes handling the recurrence cases a bit tougher as "thinking" and additional conditionals (or mod expressions, perhaps) are required to advance the state.

Here is an example of a combined recursive function (this is incorrect when x is 0). Unlike the three method approach above, the stack depth will grow to x^3 => i*j*k. This will easily kill Java's recursion limits - even for smallish values of x- as Java [7] doesn't have tail-call optimization.

void loop(int i, int j, int k) {        
    list.add(array[i] + array[j] + array[k]);

    // advance states
    k++;
    if (k == x) { k = 0; j++; }
    if (j == x) { j = 0; i++; }
    if (i == x) { i = 0; }

    // terminate on all wrap-around
    if (i == 0 && j == 0 && k == 0) { return; }

    // recurse
    loop(i, j, k);
}

[1] YMMV, for theoretical purposes only - I love recursion, but it's not suited for this case in Java.

[2] For some value of "smallish". See how deep your stack can go!

🌐
W3Schools
w3schools.com β€Ί java β€Ί java_recursion.asp
Java Recursion
Just as loops can run into the problem of infinite looping, recursive methods can run into the problem of infinite recursion. Infinite recursion is when the method never stops calling itself.
Discussions

java - Recursion using for-loop - Stack Overflow
I am currently writing a program in which I have to calculate a number recursively using a for-loop. But unfortunately, I have no idea how to correctly implement this function since my current More on stackoverflow.com
🌐 stackoverflow.com
recursion - Java For Loop into Recursive function - Stack Overflow
In that function, rewrite the loop to Β· If the loop condition is false (i >= 1024), then return Β· Else, recursive call with argument i*2. More on stackoverflow.com
🌐 stackoverflow.com
November 8, 2011
java - Change For Loop to Recursive Method - Stack Overflow
Could you please explain to me how to change this for loop to recursive I know what recursive is but I have been unable to get the number of stars to print correctly with the code as it only printi... More on stackoverflow.com
🌐 stackoverflow.com
for loop to recursion JAVA - Stack Overflow
I need to write a recursion function that discover a password in a given length, the allowed chars are a-z. I'm not allowed to use loop but i cant get that to work. here my solution with one for l... More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 2
49

Actually you should break the function down first:

A loop has a few parts:

  1. the header, and processing before the loop. May declare some new variables

  2. the condition, when to stop the loop.

  3. the actual loop body. It changes some of the header's variables and/or the parameters passed in.

  4. the tail; what happens after the loop and return result.

Or to write it out:

foo_iterative(params){
    header
    while(condition){
        loop_body
    }
    return tail
}

Using these blocks to make a recursive call is pretty straightforward:

foo_recursive(params){
    header
    return foo_recursion(params, header_vars)
}

foo_recursion(params, header_vars){
    if(!condition){
        return tail
    }

    loop_body
    return foo_recursion(params, modified_header_vars)
}

Et voilΓ ; a tail recursive version of any loop. breaks and continues in the loop body will still have to be replaced with return tail and return foo_recursion(params, modified_header_vars) as needed but that is simple enough.


Going the other way is more complicated; in part because there can be multiple recursive calls. This means that each time we pop a stack frame there can be multiple places where we need to continue. Also there may be variables that we need to save across the recursive call and the original parameters of the call.

We can use a switch to work around that:

bar_recurse(params){
    if(baseCase){
        finalize
        return
    }
    body1
    bar_recurse(mod_params)
    body2
    bar_recurse(mod_params)
    body3
}


bar_iterative(params){
    stack.push({init, params})

    while(!stack.empty){
        stackFrame = stack.pop()

        switch(stackFrame.resumPoint){
        case init:
            if(baseCase){
                finalize
                break;
            }
            body1
            stack.push({resum1, params, variables})
            stack.push({init, modified_params})
            break;
        case resum1:
            body2
            stack.push({resum2, params, variables})
            stack.push({init, modified_params})
            break;
        case resum2:
            body3
            break;
        }
    }
}
2 of 2
2

Following up on @ratchet freak's answer, I created this example of how the Fibonacci function can be rewritten to a while loop in Java. Note that There's a much simpler (and efficient) way to rewrite the Fibonacci with a while loop though.

class CallContext { //this class is similar to the stack frame

    Object[] args;

    List<Object> vars = new LinkedList<>();

    int resumePoint = 0;

    public CallContext(Object[] args) {
        this.args = args;
    }

}


static int fibonacci(int fibNumber) {
    Deque<CallContext> callStack = new LinkedList<>();
    callStack.add(new CallContext(new Object[]{fibNumber}));
    Object lastReturn = null; //value of last object returned (when stack frame was dropped)
    while (!callStack.isEmpty()) {
        CallContext callContext = callStack.peekLast();
        Object[] args = callContext.args;
        //actual logic starts here
        int arg = (int) args[0];
        if (arg == 0 || arg == 1) {
            lastReturn = arg;
            callStack.removeLast();
        } else {
            switch (callContext.resumePoint) {
                case 0: //calculate fib(n-1)
                    callStack.add(new CallContext(new Object[]{arg - 1}));
                    callContext.resumePoint++;
                    break;
                case 1: //calculate fib(n-2)
                    callContext.vars.add(lastReturn); //fib1
                    callStack.add(new CallContext(new Object[]{arg - 2}));
                    callContext.resumePoint++;
                    break;
                case 2: // fib(n-1) + fib(n-2)
                    callContext.vars.add(lastReturn); //fib2
                    lastReturn = (int) callContext.vars.get(0) + (int) callContext.vars.get(1);
                    callStack.removeLast();
                    break;
            }
        }
    }
    return (int) lastReturn;
}
🌐
Coderanch
coderanch.com β€Ί t β€Ί 629435 β€Ί java β€Ί recursion-loop-works
how recursion inside for loop works (Java in General forum at Coderanch)
February 25, 2014 - 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 ... ... can you guys tell me hoe this recursion print 3 2 1 2 1 3 2 1 2 1 3 2 1 2 1 if i call it with value 3.
🌐
Stack Overflow
stackoverflow.com β€Ί questions β€Ί 53122414 β€Ί recursion-using-for-loop
java - Recursion using for-loop - Stack Overflow
public class Calc { public static void main(String[] args) { Scanner sc = new Scanner(System.in); double k = sc.nextDouble(); double e = sc.nextDouble(); double q = sc.nextDouble(); int n = sc.nextInt(); for (int i = 0; i < n; i++) { k = (k + (i * e)) * (1 + q); //The problem I have is that I don't know how to access the previous element of the for-loop } } } ... You say you should recursion, but I don't see any method that could be called recursively.
Find elsewhere
🌐
Stack Overflow
stackoverflow.com β€Ί questions β€Ί 37104344 β€Ί for-loop-to-recursion-java
for loop to recursion JAVA - Stack Overflow
public class Password { public static void main(String[] args) { System.out.println(findPassword(0, "this is the password to find")); } public static String findPassword(int p, final String passwordToFind) { System.out.println(p); //just checkin it's working if (p == passToInt(passwordToFind)) return passwordToFind; else return findPassword(++p, passwordToFind); } private static int passToInt(String passwordToFind) { int a = 0; for (byte b : passwordToFind.getBytes()) { a += b; } return a; } } This is not the most beautiful code in the world, and I didn't go deep to see if it's really working, it's just to give you an idea of how to solve it without using a loop, but just a simple recursion.
🌐
Study.com
study.com β€Ί computer science courses β€Ί computer science 201: data structures & algorithms
Methods for Recursion vs. Iteration in Java - Lesson | Study.com
April 23, 2021 - I can research almost any subject, delve into it more deeply if I wish, and begin studying at a deeper level right away. Catherine S. ... Let's start with some definitions. When a Java function calls itself, it's known as recursion. When we ...
🌐
Quora
quora.com β€Ί How-does-recursion-work-inside-a-for-loop-Most-importantly-how-does-it-flow
How does recursion work inside a for loop? Most importantly, how does it flow? - Quora
Answer (1 of 5): Recursion IS NOT a simple thing to master. The idea is very simple, which is a function that can call itself. E.g ( fibonacci ) : A very simple code to count rabbits… anyways, the idea of recursion is to get a big problem ( what is the fibonacci of 5 ? ), and break it down into ...
Top answer
1 of 2
2

Have a look at your loops, i.e. how they are related to each other. As an example let's take the 1st and 2nd:

for (int a = 0; a < N; a++) {      
    for (int b = a + 1; b < N; b++) {      

As you can see each loop uses 3 values/variables:

  • the loop variable (a, b), let's call it x
  • the maximum value N
  • an initial value (0, a + 1), let's call it start

Thus both loops could be rewritten as

for (int x = start; x < N; x++ ) { ... }

Now put that into a method and add a condition for the recursion:

void runInnerLoop( int start, int N) {
  for (int x = start; x < N; x++ ) { 
    runInnerLoop( x + 1, N );
  }  
}

Note that in your case you'd need to also pass the list of strings as a parameter and add a string to it, either before of after the recursion.

Also note that I didn't include any additional check whether to do the recursive call or not. That way you'd eventually end up with start == N but the loop condition would take take of that. Adding a condition like if( x < N - 1 ) would prevent an unnecessary recursive call at the cost of additional condition evaluation. Which option would be faster remains to be seen but since that's probably not really relevant I'd opt for the easier to read version.

However, since you're current learing recursion: keep in mind to always check whether the abort condition can be reached in all cases or not. Otherwise you'd run into StackOverflowError etc. - which could also happen if your N is too big in which case you'd need a different approach.

Edit:

I must admit that I overlooked a piece of information in your question, i.e. there is a limited recursion depth which you called M. Thus I'll expand my answer with that information and I'll also explain how to get the "lists" you want to print.

Basically handling the recursion depth is easy: you pass the current depth + 1 to each call as well as the maximum depth and before doing a recursive call you check for depth < maxDepth - if this is true you do a recursice call, if it is false you print the current branch (i.e. the "list" of integers).

Handling the lists isn't that hard but doing it efficiently requires some thought. Basically each iteration adds a new list, i.e. 0,1,2 and 0,2,3 are different lists.

If you'd use lists you'd have to pass the current list to the recursive call and inside the loop create a new list, add all the values of the top list to it and finally add the current loop variable to it (e.g. List<Integer> list = new ArrayList<>( topList ); list.add(x);).

However, you only need the lists in the deepst calls, i.e. when printing or collecting them. This means all those intermediate lists are a waste of time and memory. So instead you might want to use a Stack to track the current loop values, i.e. at the start of an iteration you push the current value to the stack and remove the top value at the end of the iteration. That way you can reuse the same stack and print only the current loop variables (or collect them into a new list for later use).

Here's the top example using recursion depth and a stack:

void runInnerLoop( int start, int N, int depth, int maxDepth, Stack<Integer> stack) {    
  for (int x = start; x < N; x++ ) {
    stack.push( x ); //add the current value to the stack
    if( depth < maxDepth ) { //max depth not reached, do another recursion
      runInnerLoop( x + 1, N, depth + 1, maxDepth, stack );
    } else {
      System.out.println( stack ); //max depth reached, print now
    }
    stack.pop(); //remove the top value from the stack
  }  
}

The inital call for your first example (N=4, maxDepth=3) would look like this:

runInnerLoop( 0, 4, 1, 3, new Stack<>() );
2 of 2
0

Update 4

static List<List<Integer>> f(int init, int N, int depth, List<Integer> ls) {
    List<List<Integer>> all = new ArrayList<>();

    for(int i = init; i < N; i++) {
        List<Integer> ls_ = new ArrayList<Integer>();
        ls_.addAll(ls);
        ls_.add(i);
        if(depth == 0) {
            all.add(ls_);
        } else {
            all.addAll(f(i + 1, N, depth-1, ls_));
        }
    }

    return all;
}

Original

Without spoiling too much maybe this helps you:

for (int i = 0; i < 10; i++)
        System.out.println(i);

is semantically the same as:

public static void f(final int i) {
    if (i < 10) {
        System.out.println(i);
        For.f(i + 1);
    }
}

You will also notice that:

while(i < 10) {
  System.out.println(i);
  i++;
}

is basically the same thing and can be translated to recursion the same way.

I wouldn't recommend coding like this but you can rewrite every for-loop to a recursive function this way. for loops don't consume as much stack space.

When you nest for loops you can translate them using the same algorithm:

for (int x = 0; x < 3; x++)
        for (int y = 0; y < 3; y++)
            System.out.println(x + "," + y);

becomes two functions f,g:

public static void f(final int x) {
    if (x < 3) {
        For.g(x, 0);
        For.f(x + 1);
    }
}

public static void g(final int x, final int y) {
    if (y < 3) {
        System.out.println(x + "," + y);
        For.g(x, y + 1);
    }
}

Update

To answer the comments:

It doesn't matter how many for-loops you have nested. Every for-loop can be rewritten as a recursive function. If you have N nested for-loops you can rewrite them to N recursive functions. The method is as follow:

If you have for(TYPE i = INIT; CONDITION; P-EXPRESSION) { CODE } you can translate it to:

function NAME(TYPE i) {
   if(CONDITION) {
     CODE
     P-EXPRESSION
     NAME(i); //this is the recursive call
   }
}

NAME(INIT)

If you have nested for-loops the method is the same but you have to pass local variables as parameters.

for(int a = INIT_A; CONDITION_A; P-EXPRESSION_A) {
  CODE_A
  for(int b = INIT_B; CONDITION_B; P-EXPRESSION_B) {
    CODE_B
    //^- if you use a in this you have to pass a as a parameter
    for(int c = INIT_C; CONDITION_C; P-EXPRESSION_C) {
      CODE_C
      //^- same deal
    }
  }
}

Becomes roughly (pseudo-code):

function f(int a) {
  if(CONDITION_A) {
    CODE_A
    g(a, INIT_B);
    P-EXPRESSION_A
    f(a);
  }
}

function g(int a, int b) {
  if(CONDITION_B) {
    CODE_B
    h(a,b, INIT_C);
    P-EXPRESSION_B
    g(a, b);
  }
}

function h(int a, int b, int c) {
  if(CONDITION_C) {
    CODE_C
    P-EXPRESSION_C
    h(a,b,c);
  }
}

f(INIT_A)

Update 2

The direct 1:1 translation using the above method gives you:

public static List<String> f(int a, int N, List<String> stringList) {       
    if(a < N) {
        g(a, a + 1, N, stringList);
        f(a + 1, N, stringList);
    }
    return stringList;
}

public static List<String> g(int a, int b, int N, List<String> stringList) {
    if(b < N) {
        h(a, b, b+1, N, stringList);
        g(a, b+1, N, stringList);
    }
    return stringList;
}

public static List<String> h(int a, int b, int c, int N, List<String> stringList) {
    if(c < N) {
        String str = " ( " + Integer.toString(a)
        + " , " + Integer.toString(b)
        + " , " + Integer.toString(c) +" ) ";
            stringList.add(str);
        h(a, b, c+1, N, stringList);
    }
    return stringList;
}

It's not beautiful/optimal code but it's a translation of each for-loop to a recursive function.

Update 3

A nicer translation would have the form:

h a b c n
 |c < n = (a,b,c) : h a b (succ c) n
 |otherwise = []

g a b n
 |b < n = h a b (succ b) n ++ g a (succ b) n
 |otherwise = []

f a n
 |a < n = g a (succ a) n ++ f (succ a) n
 |otherwise = []

main = print $ f 0 4

but this would translate to java as:

public static List<String> f(int a, int N) {        
    if(a < N) {
        List<String> ls = new ArrayList<String>();

        ls.addAll(g(a, a + 1, N));
        ls.addAll(f(a + 1, N));

        return ls;
    }
    return new ArrayList<String>();
}

public static List<String> g(int a, int b, int N) {


    if(b < N) {

        List<String> ls = new ArrayList<String>();
        ls.addAll(h(a,b,b+1,N));
        ls.addAll(g(a,b+1,N));


        return ls;
    }
    return new ArrayList<String>();
}

public static List<String> h(int a, int b, int c, int N) {
    if(c < N) {
        String str = " ( " + Integer.toString(a)
        + " , " + Integer.toString(b)
        + " , " + Integer.toString(c) +" ) ";

        List<String> ls = new ArrayList<String>();
        ls.add(str);
        ls.addAll(h(a,b,c+1,N));

        return ls;
    }
    return new ArrayList<String>();
}

Which is not efficient Java :).

🌐
Stack Overflow
stackoverflow.com β€Ί questions β€Ί 72065588 β€Ί turn-a-for-loop-into-recursion
java - Turn a for loop into Recursion - Stack Overflow
I have a list of elements that I wanted to print out. The way it is gonna work is that when we read aloud the list [1,1,1,1,4,4,4], we most likely say four 1s and three 4s, instead of uttering each number one by one. Method readAloud(List) should return a List. ... As you can see, I have already done it. But how can I turn this code into recursion? List<Integer> answer = new ArrayList<>(); int count=1; int prev_elt = xs.get(0); for(int i=1;i<xs.size();i++){ if (prev_elt == xs.get(i)){ count += 1; } else{ answer.add(count); answer.add(prev_elt); prev_elt=xs.get(i); count=1; } if(i == xs.size()-1){ answer.add(count); answer.add(prev_elt); prev_elt=xs.get(i); count=1; } } return answer; }
🌐
Reddit
reddit.com β€Ί r/learnjava β€Ί convert for loop to a recursive function
r/learnjava on Reddit: convert for loop to a recursive function
September 30, 2020 -

can Someone help me convert this iterative function into a recursive function?

public int getMax(int [] A, int i, int j){

int max = A[i];

for (int k = i+1; k <=j ; k++) {

if(A[k]>max){

max = A[k];

}

}

return max;

}

I do not really understand recursion. I know the function will call itself at some point, but i'm pretty confused still.

Top answer
1 of 1
2
When writing recursive functions one of the first things you should think about is how you are going to make the recursion stop, i.e. what are your base cases? This is analogous to thinking about your exit conditions in a loop. In this example your base case is the same as your for loops stopping point, you want to exit when some counter, k, is greater than or equal to j. Each recursive call will need to modify the k variable in a similar way as the for loop is modifying it with each iteration, k++. You also need to think about what you want to do when you actually hit your base case, in this instance you want to return the max value. some pseudo code to get you started: public int getMax(int[] A, int i, int j, int k, int max){ // note the changes to the function signature // base cases // if k > j, return max; -- found the max, return it // else // find max so far: if (A[k] > max) max = A[k]; // recurse by calling getMax with the next k value and the new max, and returning the result of that recursive call // return getMax(...) } I assume this is a homework problem, if you're allowed to change the variable names it would be nice to change i to "start" and j to "end" and k to "i" since i is traditionally used for the current index, and would make reading the code a bit more clear. Recursion can be hard to grasp at first, try working through the code step by step, literally writing down the variable values for each function call and what they will return. You'll notice that one function is kindof "paused" when it calls itself and you have a new set of variables to work through. Once you finally "bottom out" and hit the base case that doesn't recurse, all your function calls will start "rubberbanding" back their return values upwards until the original function call itself returns.
🌐
Programiz
programiz.com β€Ί java-programming β€Ί recursion
Java Recursion: Recursive Methods (With Examples)
Any object in between them would be reflected recursively. ... In the above example, we have called the recurse() method from inside the main method (normal method call). And, inside the recurse() method, we are again calling the same recurse method. This is a recursive call.
🌐
Baeldung
baeldung.com β€Ί home β€Ί java β€Ί core java β€Ί recursion in java
Recursion in Java | Baeldung
January 2, 2026 - We’ll explain the characteristics of a recursive function and show how to use recursion for solving various problems in Java.
🌐
Princeton CS
introcs.cs.princeton.edu β€Ί java β€Ί 23recursion
Recursion
May 24, 2020 - The function-call mechanism in Java supports this possibility, which is known as recursion. The "Hello, World" for recursion is the factorial function, which is defined for positive integers n by the equation Β· $$n! = n \times (n-1) \times (n-2) \times \; \ldots \; \times 2 \times 1$$ The quantity n! is easy to compute with a for loop...
🌐
Jct
danzig.jct.ac.il β€Ί java_class β€Ί recursion.html
Java Recursion with examples
A simple base case which we have a solution for and a return value. A way of getting our problem closer to the base case. I.e. a way to chop out part of the problem to get a somewhat simpler problem. A recursive call which passes the simpler problem back into the method. The key to thinking recursively is to see the solution to the problem as a smaller version of the same problem.
🌐
Stack Overflow
stackoverflow.com β€Ί questions β€Ί 49390635 β€Ί convert-recursion-to-loop-or-another-faster-solution
java - Convert Recursion to Loop or another faster solution - Stack Overflow
Will be another way to make this method faster? recursion: public static int MOD = 11380; public static int[][][][] memo = new int[11][11][11][31]; static int ret; public static int solve(int L1, int L2, int L3, int D) { if (D < 0) { return 0; } if (L1 + L2 + L3 == 0) { return 1; } ret = memo[L1][L2][L3][D]; if (ret == 0) { // ret = 0; for (int i = 0; i < L1; ++i) { for (int j = 0; j <= L2; ++j) { for (int k = 0; k <= L3; ++k) { ret += solve(i, j, k, D - 1) *solve(L1 - 1 - i, L2 - j, L3 - k, D); ret %= MOD; } } } for (int i = 0; i < L2; ++i) { for (int j = 0; j <= L3; ++j) { ret += solve(0, i, j, D - 1) * solve(L1, L2 - 1 - i, L3 - j, D); ret %= MOD; } } for (int i = 0; i < L3; ++i) { ret += solve(0, 0, i, D - 1) * solve(L1, L2, L3 - 1 - i, D); ret%= MOD; } } return ret; }
Top answer
1 of 2
2

Your problem is not in the part you posted.

I added dummy implementations for all the classes and methods used in your method, and it runs quite fine, stopping at level 6.

package de.fencing_game.paul.examples;

import java.util.*;

public class RecursionAndLoop {


    private static class Move {
        private String id;
        public Move(String type) {
            this.id = type;
        }
        public String toString(){
            return "Move(" + id + ")";
        }

    }


    private static class GameState {
        private static int nextID;

        private int id;

        GameState() {
            this.id = nextID++;
        }

        public GameState getNewInstance(Move move) {
            return new GameState();
        }

        public int getPossibleMoveCount(int index) {
            return 5;
        }

        public Vector<Move> getPossibleMoves(int index) {
            Vector<Move> v = new Vector<Move>();
            for(int i = 0; i < 5; i++) {
                v.add(new Move(index + "Γ—" + i));
            }
            return v;
        }

        public int getMarkCount(int index) {
            return 20 + index;
        }

        public String toString() {
            return "GameState[" + id + "]";
        }
    }

    private static class Node {
        private GameState state;
        private Move move;

        private List<Node> children;
        private Node parent;
        private int score;

        public Node(GameState s, Move m) {
            this.children = new ArrayList<Node>();
            this.state = s;
            this.move = m;
        }

        public void addChild(Node child) {
            children.add(child);
        }

        public void setParent(Node node) {
            parent = node;
        }

        public void setScore(int neu) {
            this.score = neu;
        }

        public int getDepth() {
            if(parent == null) {
                return 0;
            }
            return 1 + parent.getDepth();
        }

        /**
         * prints a simple tree view of this ZipNode and its descendants
         * on {@link System.out}.
         * @param prefix a prefix string to add before all lines.
         * @param self a prefix string to add before the line of this node
         *    itself (after the general prefix).
         * @param sub a prefix string to add before the line of all subnodes
         *    of this node (after the general prefix).
         */
        private void printTree(String prefix,
                               String self,
                               String sub) {
            System.out.println(prefix + self + state + " - " + move +
                               " - " + score);
            String subPrefix = prefix + sub;
            // the prefix strings for the next level.
            String nextSelf = " β”œβ”€ ";
            String nextSub =  " β”‚ ";
            Iterator<Node> iterator =
                this.children.iterator();
            while(iterator.hasNext()) {
                Node child = iterator.next();
                if(!iterator.hasNext() ) {
                    // last item, without the "|"
                    nextSelf = " └─ ";
                    nextSub =  "   ";
                }
                child.printTree(subPrefix, nextSelf, nextSub);
            }
        }



    }


    int switchIndex(int index) {
        return index + 1;
    }



    private void makeTree(GameState prevState, Vector<Move> moves, Node parentNode, int index, int depthLimit) {

        if(prevState.getPossibleMoveCount(index) != 0){

            for(int i = 0; i < moves.size(); i++){

                Move thisMove = moves.get(i);
                GameState newState = prevState.getNewInstance(thisMove);
                Node child = new Node(newState, thisMove);
                parentNode.addChild(child);
                child.setParent(parentNode);

                if((child.getDepth() + 1) < depthLimit){

                    int newIndex = switchIndex(index);
                    Vector<Move> newMoves = newState.getPossibleMoves(newIndex);
                    makeTree(newState, newMoves, child, newIndex, depthLimit);

                }else{

                    child.setScore(newState.getMarkCount(index));
                }
            }
        }
    }


    public static void main(String[] params) {
        GameState start = new GameState();
        Vector<Move> m = new Vector<Move>();
        m.add(new Move("start"));
        Node root = new Node(start, null);
        int index = 7;
        int depthLimit = 6;
        new RecursionAndLoop().makeTree(start, m, root, index, depthLimit);
        root.printTree("", " ", "");
    }

}

(I changed a bit to generic types to avoid compiler warnings.)

Here is the output for depthLimit=4:

GameState[0] - null - 0
└─ GameState[1] - Move(start) - 0
   β”œβ”€ GameState[2] - Move(8Γ—0) - 0
   β”‚  β”œβ”€ GameState[3] - Move(9Γ—0) - 29
   β”‚  β”œβ”€ GameState[4] - Move(9Γ—1) - 29
   β”‚  β”œβ”€ GameState[5] - Move(9Γ—2) - 29
   β”‚  β”œβ”€ GameState[6] - Move(9Γ—3) - 29
   β”‚  └─ GameState[7] - Move(9Γ—4) - 29
   β”œβ”€ GameState[8] - Move(8Γ—1) - 0
   β”‚  β”œβ”€ GameState[9] - Move(9Γ—0) - 29
   β”‚  β”œβ”€ GameState[10] - Move(9Γ—1) - 29
   β”‚  β”œβ”€ GameState[11] - Move(9Γ—2) - 29
   β”‚  β”œβ”€ GameState[12] - Move(9Γ—3) - 29
   β”‚  └─ GameState[13] - Move(9Γ—4) - 29
   β”œβ”€ GameState[14] - Move(8Γ—2) - 0
   β”‚  β”œβ”€ GameState[15] - Move(9Γ—0) - 29
   β”‚  β”œβ”€ GameState[16] - Move(9Γ—1) - 29
   β”‚  β”œβ”€ GameState[17] - Move(9Γ—2) - 29
   β”‚  β”œβ”€ GameState[18] - Move(9Γ—3) - 29
   β”‚  └─ GameState[19] - Move(9Γ—4) - 29
   β”œβ”€ GameState[20] - Move(8Γ—3) - 0
   β”‚  β”œβ”€ GameState[21] - Move(9Γ—0) - 29
   β”‚  β”œβ”€ GameState[22] - Move(9Γ—1) - 29
   β”‚  β”œβ”€ GameState[23] - Move(9Γ—2) - 29
   β”‚  β”œβ”€ GameState[24] - Move(9Γ—3) - 29
   β”‚  └─ GameState[25] - Move(9Γ—4) - 29
   └─ GameState[26] - Move(8Γ—4) - 0
      β”œβ”€ GameState[27] - Move(9Γ—0) - 29
      β”œβ”€ GameState[28] - Move(9Γ—1) - 29
      β”œβ”€ GameState[29] - Move(9Γ—2) - 29
      β”œβ”€ GameState[30] - Move(9Γ—3) - 29
      └─ GameState[31] - Move(9Γ—4) - 29
2 of 2
0

When you call

makeTree(newState, newMoves, child, newIndex, depth);

inside of your if statement where are you expecting depth to come from? It looks like you're passing in depth to the makeTree routine, yet expecting it to be the depth of the current node (this.depth maybe?)