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.
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:
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?
A loopA base caseThe garbage collectorA return type
Show answer
Answer: A base case
Practice next
- Climbing Stairs · coding problem
- Maximum Depth of Binary Tree · coding problem