- Example 1:
print before recursion : first print and then do recursion.
public static void printSth(int n) {
if (n > 3) {
return;
}
System.out.print(n + " ");
printSth(n + 1);
}
public static void main(String[] args) {
printSth(1);
}
- Analysis:
- how n changes: 1 2 3 4
- when print is executed: n = 1, 2, 3 (when n is 4, return, no printing)
- Print result: 1 2 3
- Process:

- Example 2:
print after recursion : first do recursion and then print when recursion is done, so printing is done reversely.
public static void printSth(int n) {
if (n > 3) {
return;
}
printSth(n + 1);
System.out.print(n + " ");
}
public static void main(String[] args) {
printSth(1);
}
- Analysis:
- how n changes: 1 2 3 4
- when print is executed: n = 1, 2, 3 (when n is 4, return, no printing)
- Print result: 3 2 1
- Process:

- Example 3:
multiple recursion in a method.
public static int recur(int n) {
if (n <= 1) {
return 1;
} else {
return (recur(n - 2) + recur(n - 1));
}
}
public static void main(String[] args) {
System.out.println(recur(4));
}
- Analysis:
- recur(4) -> recur(2) + recur(3)
- recur(2) -> recur(0) + recur(1) = 1 + 1 = 2
- recur(3) -> recur(1) + recur(2) = 1 + 2 = 3
- so, recur(4) = recur(2) + recur(3) = 2 + 3 = 5