
- Functional Programming with Java Tutorial
- Home
- Overview
- Aspects
- Functions
- Functional Composition
- Eager vs Lazy Evaluation
- Persistent Data Structure
- Recursion
- Parallelism
- Optionals & Monads
- Closure
- Currying
- Reducing
- Java 8 Onwards
- Lambda Expressions
- Default Methods
- Functional Interfaces
- Method References
- Constructor References
- Collections
- Functional Programming
- High Order Functions
- Returning a Function
- First Class Functions
- Pure Functions
- Type Inference
- Exception Handling
in Lambda Expressions - Streams
- Intermediate Methods
- Terminal methods
- Infinite Streams
- Fixed Length Streams
- Useful Resources
- Quick Guide
- Resources
- Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Functional Programming with Java - Recursion
Recursion is calling a same function in a function until certain condition are met. It helps in breaking big problem into smaller ones. Recursion also makes code more readable and expressive.
Imperative vs Recursive
Following examples shows the calculation of sum of natural numbers using both the techniques.
public class FunctionTester { public static void main(String[] args) { System.out.println("Sum using imperative way. Sum(5) : " + sum(5)); System.out.println("Sum using recursive way. Sum(5) : " + sumRecursive(5)); } private static int sum(int n){ int result = 0; for(int i = 1; i <= n; i++){ result = result + i; } return result; } private static int sumRecursive(int n){ if(n == 1){ return 1; }else{ return n + sumRecursive(n-1); } } }
Output
Sum using imperative way. Sum(5) : 15 Sum using recursive way. Sum(5) : 15
Using recursion, we are adding the result of sum of n-1 natural numbers with n to get the required result.
Tail Recursion
Tail recursion says that recursive method call should be at the end. Following examples shows the printing of a number series using tail recursion.
public class FunctionTester { public static void main(String[] args) { printUsingTailRecursion(5); } public static void printUsingTailRecursion(int n){ if(n == 0) return; else System.out.println(n); printUsingTailRecursion(n-1); } }
Output
5 4 3 2 1
Head Recursion
Head recursion says that recursive method call should be in the beginning of the code. Following examples shows the printing of a number series using head recursion.
public class FunctionTester { public static void main(String[] args) { printUsingHeadRecursion(5); } public static void printUsingHeadRecursion(int n){ if(n == 0) return; else printUsingHeadRecursion(n-1); System.out.println(n); } }
Output
1 2 3 4 5
Advertisements