Java Recursion

JK 2014 
Created at
Updated at  
7,188 0 0

Recursion is the technique of making a function call itself. This technique provides a way to break complicated problems down into simple problems which are easier to solve.

Recursion may be a bit difficult to understand. The best way to figure out how it works is to experiment with it.


Recursion Example

Adding two numbers together is easy to do, but adding a range of numbers is more complicated. In the following example, recursion is used to add a range of numbers together by breaking it down into the simple task of adding two numbers:

public class Main {
  public static void main(String[] args) {
    int result = sum(10);
    System.out.println(result);
  }
  public static int sum(int k) {
    if (k > 0) {
      return k + sum(k - 1);
    } else {
      return 0;
    }
  }
}

When the sum() function is called, it adds parameter k to the sum of all numbers smaller than k and returns the result. When k becomes 0, the function just returns 0. When running, the program follows these steps:

10 + sum(9)
10 + ( 9 + sum(8) )
10 + ( 9 + ( 8 + sum(7) ) )
...
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0

Since the function does not call itself when k is 0, the program stops there and returns the result.


Halting Condition

Just as loops can run into the problem of infinite looping, recursive functions can run into the problem of infinite recursion. Infinite recursion is when the function never stops calling itself. Every recursive function should have a halting condition, which is the condition where the function stops calling itself. In the previous example, the halting condition is when the parameter k becomes 0.

It is helpful to see a variety of different examples to better understand the concept. In this example, the function adds a range of numbers between a start and an end. The halting condition for this recursive function is when end is not greater than start:

public class Main {
  public static void main(String[] args) {
    int result = sum(5, 10);
    System.out.println(result);
  }
  public static int sum(int start, int end) {
    if (end > start) {
      return end + sum(start, end - 1);
    } else {
      return end;
    }
  }
}

 

Tags Java Java Recursion Facebook X
Comments 0
Similar posts
  1. Java Scope
    7,079
  2. Java Methods
    7,071
  3. Java Classes and Objects
    7,069
  4. Java While Loop/Do While Loop/For Loop/For-Each Loop/Break/Continue
    7,832
  5. Java Switch Statements
    7,391
  6. Java Short Hand If...Else (Ternary Operator)
    7,562
  7. Java If ... Else
    7,381
  8. Java Packages
    7,163
  9. Java Inheritance (Subclass and Superclass)
    7,172
  10. Java Math
    7,425
  11. Java Variables
    7,448
  12. Java Comments
    7,983
  13. Java Polymorphism
    7,047
  14. The Print() Method
    7,141
  15. Java Syntax
    7,428
  16. Java Getting Started
    7,393
  17. Java Inner Classes
    7,033
  18. What is Java?
    7,080
  19. Machine Learning Types and Programming Languages
    7,223
  20. Java Tutorials associated with AP Computer Science A
    7,584
  21. Creating a simple Java Servlet (Web Server Page) with Apache Maven on Microsoft Windows
    7,156
  22. Java Servlet Example
    7,111
  23. Difference between Java and Javascript
    7,595
  24. Challenge: One Code Problem Per Day
    1,081
  1. Java Servlet Example
    7,111
  2. How do I replace content that based on the HTML UI Template
    7,146
  3. Creating a simple Java Servlet (Web Server Page) with Apache Maven on Microsoft Windows
    7,156
  4. Dataset of California Foodbanks
    7,160
  5. Java Tutorials associated with AP Computer Science A
    7,584
  6. Java Inner Classes
    7,033
  7. Java Polymorphism
    7,047
  8. Java Inheritance (Subclass and Superclass)
    7,172
  9. Java Packages
    7,163
  10. Java Abstract Classes and Methods
    7,699
  11. Java Classes and Objects
    7,069
  12. Java Scope
    7,079
  13. Java Methods
    7,071
  14. Java Arrays
    8,650
  15. Java While Loop/Do While Loop/For Loop/For-Each Loop/Break/Continue
    7,832
  16. Java Switch Statements
    7,391
  17. Java Short Hand If...Else (Ternary Operator)
    7,562
  18. Java If ... Else
    7,381
  19. Java Math
    7,425
  20. Java Variables
    7,448
  21. Java Comments
    7,983
  22. The Print() Method
    7,141
  23. Java Syntax
    7,428
  24. Java Getting Started
    7,393
  25. What is Java?
    7,080
Recently updated
  1. Michael Jackson's Billie Jean
    67
  2. Bootstrap vs. Tailwind CSS: Origins, Features, Pros & Cons, and How to Choose the Right Framework
    120
  3. The Complete Guide to Golang: History, Features, Real-World Uses, and Code Examples
    332
  4. Telemetry vs. Analytics: Understanding the Difference and Why It Matters
    211
  5. The Evolution and Production Reality of Agentic AI
    198
  6. How to Activate or Waive Your UIUC Student Health Insurance
    281
  7. Complete Guide to Building a Machine Learning Model
    316
  8. My life cuts at Las Vegas during Thanksgiving day holiday
    7,396
  9. The Cybercab Transformation: From Autonomous Taxi to Mobile Base Station
    342
  10. Harness vs. OpenClaw: Two Very Different "Agents"
    956
  11. Clean Python Environments: The Power of venv vs. Docker
    812
  12. What is Docker? Why is Docker also useful in a development environment?
    609
  13. UIUC 2026-2027 Academic Calendar
    1,565
  14. How to Build Llama 3 AI Apps with Python: Setup & User Prompts
    800
  15. Open-Source LLMs: The AI Revolution
    746
  16. Resume 2.0: Leveling Up for My First Software Gig
    2,190
  17. Not everyone will understand what this man just did
    1,817
  18. UIUC Dorm Guide: Find Your Perfect Fit !!
    1,579
  19. Unpacking IU's Shopper
    747
  20. Jackie Chan's Police Story: The Action Masterpiece
    646
  21. The IVE Story: Identity, 'I AM' Charts, and Influence
    947
  22. Tech Visionaries who graduated at UIUC - You are the Next Turn
    1,182
  23. Open Databases for Sex Crime Occurrences in the U.S.
    710
  24. Automatically copy text to the clipboard when dragging the mouse in the Cursor
    2,602
  25. My First Day at University of Illinois-Urvana Champaign
    1,179
  26. Sand, Sea, and a Splash of Fun at Newport Beach: A Family Adventure
    8,118
  27. Sun, Rocks, and Adventure: A Day at Joshua Tree National Park
    8,197
  28. Sipping the Stars: My Starbucks Adventure
    9,630
  29. Exciting explore at Sequoia National Park
    7,647
  30. My Life Shot at Death Valley
    1,687
  31. Ip Man fights with Muay Thai Master
    928
  32. Mad Clown - Don't Die
    1,009
  33. How to get Student Enrollment and Degree Verification at UIUC
    4,818
  34. LAX Thanksgiving Rush: A Joyful Reunion
    917
  35. ZO ZAZZ(조째즈) - Don`t you know (모르시나요) (PROD.ROCOBERRY)
    1,116
  36. FISHINGIRLS Unleashes Energetic EP 'Funiverse' Featuring Signature Track 'Fishing King'
    970
  37. 10CM - To Reach You (너에게 닿기를)
    1,151
  38. Feeling weak? Transform yourself at the UIUC ARC!
    1,567
  39. BOYNEXTDOOR - If I Say I Love You
    1,181
  40. The Future of Software Engineer - AI Engineering
    924
  41. G Dragon x Taeyang (Eyes Nose Lips, Power, Home Sweet Home, GOOD BOY) - LE GALA PIÈCES JAUNES 2025
    898
  42. Lie - Legend song by BIGBANG
    7,808
  43. Why ROLLBACK is useful when you work with Google Gemini CLI?
    826
  44. Reimbursement after Vaccination at McKinley Health Center
    1,012
  45. Gemini CLI makes a Magic! Time to speed up your app development with Google Gemini CLI!
    961
  46. Common Questions from UIUC school life in terms of CS Program
    1,113
  47. UIUC Immunization Compliance
    1,205
  48. LEE CHANHYUK's songs really resonate with my soul - Time Stop! Vivid LaLa Love, Eve, Endangered Love ...
    1,085
  49. LEE CHANHYUK - Endangered Love (멸종위기사랑)
    1,089
  50. Cupid (OT4/Twin Ver.) - LIVE IN STUDIO | FIFTY FIFTY (피프티피프티)
    863