Java Recursion

JK JK 2038 
Created at
Updated at  
7,305 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,226
  2. Java Methods
    7,210
  3. Java Classes and Objects
    7,236
  4. Java While Loop/Do While Loop/For Loop/For-Each Loop/Break/Continue
    8,106
  5. Java Switch Statements
    7,548
  6. Java Short Hand If...Else (Ternary Operator)
    7,727
  7. Java If ... Else
    7,541
  8. Java Packages
    7,296
  9. Java Inheritance (Subclass and Superclass)
    7,283
  10. Java Math
    7,582
  11. Java Variables
    7,624
  12. Java Comments
    8,258
  13. Java Polymorphism
    7,162
  14. The Print() Method
    7,280
  15. Java Syntax
    7,608
  16. Java Getting Started
    7,538
  17. Java Inner Classes
    7,194
  18. What is Java?
    7,190
  19. Machine Learning Types and Programming Languages
    7,375
  20. Java Tutorials associated with AP Computer Science A
    7,824
  21. Creating a simple Java Servlet (Web Server Page) with Apache Maven on Microsoft Windows
    7,294
  22. Java Servlet Example
    7,225
  23. Difference between Java and Javascript
    7,796
  24. Challenge: One Code Problem Per Day
    1,337
  1. How do I replace content that based on the HTML UI Template
    7,257
  2. Dataset of California Foodbanks
    7,275
  3. Java Abstract Classes and Methods
    7,970
  4. Java Arrays
    9,188
Recently updated
  1. Comprehensive Guide to Recent Critical PHP Vulnerabilities
    1,179
  2. How to Check Your UIUC Graduation Progress Using DARS Audit
    1,046
  3. Michael Jackson's Billie Jean
    465
  4. Meet A2O Lite: Korea's Newest K-Pop Cuties with Addictively Catchy Melodies
    449
  5. Why You Can't Stop Watching Jack Bryan's Beatbox Gaming Shorts
    385
  6. Song So-hee: The Soulful Voice Touching Hearts Through Korean Music
    425
  7. Watch This Dazzling Dancer’s Mind-Blowing Moves
    421
  8. Bootstrap vs. Tailwind CSS: Origins, Features, Pros & Cons, and How to Choose the Right Framework
    456
  9. The Complete Guide to Golang: History, Features, Real-World Uses, and Code Examples
    1,570
  10. Telemetry vs. Analytics: Understanding the Difference and Why It Matters
    608
  11. The Evolution and Production Reality of Agentic AI
    485
  12. How to Activate or Waive Your UIUC Student Health Insurance
    625
  13. Complete Guide to Building a Machine Learning Model
    625
  14. My life cuts at Las Vegas during Thanksgiving day holiday
    7,674
  15. The Cybercab Transformation: From Autonomous Taxi to Mobile Base Station
    638
  16. Harness vs. OpenClaw: Two Very Different "Agents"
    1,423
  17. Clean Python Environments: The Power of venv vs. Docker
    1,164
  18. What is Docker? Why is Docker also useful in a development environment?
    864
  19. UIUC 2026-2027 Academic Calendar
    2,170
  20. How to Build Llama 3 AI Apps with Python: Setup & User Prompts
    1,142
  21. Open-Source LLMs: The AI Revolution
    1,034
  22. Resume 2.0: Leveling Up for My First Software Gig
    3,197
  23. Not everyone will understand what this man just did
    2,624
  24. UIUC Dorm Guide: Find Your Perfect Fit !!
    1,922
  25. Unpacking IU's Shopper
    1,020
  26. Jackie Chan's Police Story: The Action Masterpiece
    919
  27. The IVE Story: Identity, 'I AM' Charts, and Influence
    1,270
  28. Tech Visionaries who graduated at UIUC - You are the Next Turn
    1,450
  29. Open Databases for Sex Crime Occurrences in the U.S.
    1,037
  30. Automatically copy text to the clipboard when dragging the mouse in the Cursor
    3,602
  31. My First Day at University of Illinois-Urvana Champaign
    1,416
  32. Sand, Sea, and a Splash of Fun at Newport Beach: A Family Adventure
    8,501
  33. Sun, Rocks, and Adventure: A Day at Joshua Tree National Park
    8,553
  34. Sipping the Stars: My Starbucks Adventure
    10,303
  35. Exciting explore at Sequoia National Park
    7,910
  36. My Life Shot at Death Valley
    2,152
  37. Ip Man fights with Muay Thai Master
    1,185
  38. Mad Clown - Don't Die
    1,312
  39. How to get Student Enrollment and Degree Verification at UIUC
    6,183
  40. LAX Thanksgiving Rush: A Joyful Reunion
    1,137
  41. ZO ZAZZ(조째즈) - Don`t you know (모르시나요) (PROD.ROCOBERRY)
    1,409
  42. FISHINGIRLS Unleashes Energetic EP 'Funiverse' Featuring Signature Track 'Fishing King'
    1,187
  43. 10CM - To Reach You (너에게 닿기를)
    1,377
  44. Feeling weak? Transform yourself at the UIUC ARC!
    1,784
  45. BOYNEXTDOOR - If I Say I Love You
    1,430
  46. The Future of Software Engineer - AI Engineering
    1,149
  47. G Dragon x Taeyang (Eyes Nose Lips, Power, Home Sweet Home, GOOD BOY) - LE GALA PIÈCES JAUNES 2025
    1,153
  48. Lie - Legend song by BIGBANG
    8,059
  49. Why ROLLBACK is useful when you work with Google Gemini CLI?
    1,147
  50. Reimbursement after Vaccination at McKinley Health Center
    1,267