
- 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 - Pure Function
A function is considered as Pure Function if it fulfils the following two conditions −
It always returns the same result for the given inputs and its results purely depends upon the inputs passed.
It has no side effects means it is not modifying any state of the caller entity.
Example- Pure Function
public class FunctionTester { public static void main(String[] args) { int result = sum(2,3); System.out.println(result); result = sum(2,3); System.out.println(result); } static int sum(int a, int b){ return a + b; } }
Output
5 5
Here sum() is a pure function as it always return 5 when passed 2 and 3 as parameters at different times and has no side effects.
Example- Impure Function
public class FunctionTester { private static double valueUsed = 0.0; public static void main(String[] args) { double result = randomSum(2.0,3.0); System.out.println(result); result = randomSum(2.0,3.0); System.out.println(result); } static double randomSum(double a, double b){ valueUsed = Math.random(); return valueUsed + a + b; } }
Output
5.919716721877799 5.4830887819586795
Here randomSum() is an impure function as it return different results when passed 2 and 3 as parameters at different times and modifies state of instance variable as well.
Advertisements