Fundamentals 7 min read

Understanding Recursion in Java: Concepts, Pros/Cons, and Practical Examples

This article explains the fundamentals of recursion in Java, covering its definition, advantages and disadvantages, differences from iteration, and provides practical examples such as traversing comment and department trees, along with code snippets, performance considerations, and improvement strategies using depth control and Stream API.

Java Captain
Java Captain
Java Captain
Understanding Recursion in Java: Concepts, Pros/Cons, and Practical Examples

The author introduces recursion through two closely related scenarios encountered in recent projects: comment tree structures and department tree structures, explaining the need to retrieve all child comment IDs or department IDs under a given parent.

Recursion in Java is defined as a method calling itself, relying on the call stack to create a new stack frame for each invocation. Proper termination conditions are essential to avoid infinite loops and stack overflow.

Advantages of recursion include simplifying complex problems by breaking them into smaller sub‑problems and enabling efficient algorithms for tasks like tree traversal. Disadvantages involve the risk of stack overflow, performance overhead from multiple stack frames, and potentially reduced readability.

The article contrasts recursion with iteration, illustrating iteration with a Java @Test method that processes a list using a for‑each loop and conditional replacement.

@Test
public void iterationTest(){
    ArrayList
list = new ArrayList<>();
    list.add("计算机技术");
    list.add("土木工程");
    list.add("市场营销");
    list.forEach(val -> {
        if (val.contains("计算机")){
            log.info("迭代前的的专业名称:{}", val);
            String str = val.replace(val, "计算机科学与技术");
            log.info("迭代后的的专业名称:{}", str);
        }
    });
}

A practical recursive example retrieves all child comment IDs under a specific comment. The article shows a simplified comment table schema and a diagram of the comment hierarchy.

/**
 * External interface that obtains recursive results
 * @param id
 */
private List
getIdListMethod(Integer id){
    ArrayList
idList = new ArrayList<>();
    this.getAllIdByRecursion(id, idList);
    log.info("递归后得到的id集合:{}", idList);
    return idList;
}

/**
 * Recursive process
 * @param id
 * @param idList
 */
private void getAllIdByRecursion(Integer id, List
idList){
    LambdaQueryWrapper
wrapper = new LambdaQueryWrapper<>();
    // Find first‑level child IDs under the given ID
    wrapper.eq(Comment::getParentId, id).eq(Comment::getStatus, NumberUtils.INTEGER_ONE);
    List
commentList = this.list(wrapper);
    for (Comment children : commentList){
        this.getAllIdByRecursion(children.getId(), idList);
    }
    log.info("放入集合的id为:{}", id);
    idList.add(id);
}

The resulting ID collection is [21,28,31,29,32], demonstrating a depth‑first traversal order.

Improvement suggestions include controlling recursion depth (e.g., JVM stack size with java -Xss5m or manually limiting depth in code) and using Java Streams for in‑memory processing when the total data size is modest (e.g., department trees with a few hundred entries).

In conclusion, while excessive recursion is discouraged in production projects, judicious use can be a powerful tool for specific problems, provided developers manage depth and consider alternative approaches when appropriate.

BackendJavaalgorithmCode ExampleRecursionTree Traversal
Java Captain
Written by

Java Captain

Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.