```public class StackTest {
public static void test1() {
System.out.println("In test1");
test2();
System.out.println("In test1 after test2");
}

public static void test2() {
System.out.println("In test2");
int y = 0;
int x = 3 / y;
}

public static void main(String[] args) {
System.out.println("In main");
test1();
}
}```

```public static int factorial(int n)
{
if (n == 0)
return 1;
else
return n * factorial(n-1);
}```

```factorial(5) returns 5 * factorial(4)
factorial(4) returns 4 * factorial(3)
factorial(3) returns 3 * factorial(2)
factorial(2) returns 2 * factorial(1)
factorial(1) returns 1 * factorial(0)
factorial(0) returns 1```

`factorial(0)`执行完成之后，可以把每一步的结果代回到上一步中，模拟堆栈的弹出。这样我们又可以一步一步回到栈底（草稿纸上的顺序是从下往上）。

```factorial(5) returns 5 * factorial(4) = 5 * 24 = 120
factorial(4) returns 4 * factorial(3) = 4 * 6 = 24
factorial(3) returns 3 * factorial(2) = 3 * 2 = 6
factorial(2) returns 2 * factorial(1) = 2 * 1 = 2
factorial(1) returns 1 * factorial(0) = 1 * 1 = 1
factorial(0) returns 1```

0:00

Given the method defined below what does the following return: `factorial(6)`?

```public static int factorial(int n)
{
if (n == 0)
return 1;
else
return n * factorial(n-1);
}```

3

Given the method defined below what does the following return: `mystery(5)`?

```public static int mystery(int n)
{
if (n == 0)
return 1;
else
return 2 * mystery (n - 1);
}```

2

Given the method defined below what does the following print: `mystery(4,3)`?

```public static int mystery(int n, int a)
{
if (n == 1) return a;
return a * mystery(n-1,a);
}```

2

```public static int bunnyEars(int bunnies)
{
if (bunnies == 0) return 0;
else if (bunnies == 1) return 2;
else return 2 + bunnyEars(bunnies - 1);
}```

```bunnyEars(5) returns 2 + bunnyEars(4)
bunnyEars(4) returns 2 + bunnyEars(3)
bunnyEars(3) returns 2 + bunnyEars(2)
bunnyEars(2) returns 2 + bunnyEars(1)
bunnyEars(1) returns 2```

```bunnyEars(5) returns 2 + bunnyEars(4) = 2 + 8 = 10
bunnyEars(4) returns 2 + bunnyEars(3) = 2 + 6 = 8
bunnyEars(3) returns 2 + bunnyEars(2) = 2 + 4 = 6
bunnyEars(2) returns 2 + bunnyEars(1) = 2 + 2 = 4
bunnyEars(1) returns 2```

Given the method defined below what does the following print: `mystery(1234)`?

```public static void mystery (int x) {
System.out.print(x % 10);

if ((x / 10) != 0) {
mystery(x / 10);
}
System.out.print(x % 10);
}```

4

Given the method defined below what does the following return: `mystery("xyzxyxy")`?

```public static int mystery(String str)
{
if (str.length() == 1) return 0;
else
{
if (str.substring(0,1).equals("y")) return 1 +
mystery(str.substring(1));
else return mystery(str.substring(1));
}
}```

2