Java Tutorial · Methods · Lesson 18 of 37

Java Scope and Recursion

Where variables are visible, and methods that call themselves.

Scope

A variable exists only inside the block { } where it's declared. Variables declared in a method are local to that method; a loop variable exists only inside the loop.

Example 1
public class Main {
    public static void main(String[] args) {
        int total = 0;
        for (int i = 1; i <= 3; i++) {
            int squared = i * i;   // exists only inside the loop body
            total += squared;
        }
        // System.out.println(squared);  // compile error: cannot find symbol
        System.out.println("total = " + total);
    }
}

Output

total = 14

Run this on your computer — see “Get Started” for setup.

Recursion

A recursive method calls itself on a smaller problem until it reaches a base case:

Example 2
public class Main {
    public static void main(String[] args) {
        System.out.println(factorial(5));
        System.out.println(fib(10));
        System.out.println(sumDigits(9045));
    }

    static long factorial(int n) {
        if (n <= 1) return 1;          // base case
        return n * factorial(n - 1);   // recursive case
    }

    static int fib(int n) {
        return n < 2 ? n : fib(n - 1) + fib(n - 2);
    }

    static int sumDigits(int n) {
        return n < 10 ? n : n % 10 + sumDigits(n / 10);
    }
}

Output

120
55
18

Run this on your computer — see “Get Started” for setup.

Every recursive call uses stack memory; very deep recursion throws StackOverflowError. Recursion is the natural way to work with trees — try Maximum Depth of Binary Tree and Climbing Stairs.

Test yourself

What stops a recursive method from calling itself forever?

  1. A loop
  2. A base case
  3. The garbage collector
  4. A return type
Show answer

Answer: A base case

Practice next