Functional Programming in Java — Simple Explanation with Examples
Functional Programming (FP) is a programming style that focuses on what to compute rather than how to do it, by using functions, immutability, and declarative code.
Java supports functional programming features since Java 8, making it a hybrid language (Object-Oriented + Functional).
🧠 What Is Functional Programming?
In simple terms:
Functional programming means writing code using functions that do not change data, and instead return new results.
Key idea:
Same input always produces the same output.
🔑 Core Principles (Simple)
1️⃣ Pure Functions
-
Output depends only on input
-
No external state modification
2️⃣ Immutability
-
Data is not modified after creation
3️⃣ Declarative Style
Say what you want, not how to loop.
4️⃣ Functions as Values
Functions can be:
-
passed as arguments
-
stored in variables
❓ Does Java Support Functional Programming?
✅ Yes (Since Java 8)
Java supports functional programming through:
-
Lambda expressions
-
Functional interfaces
-
Streams API
-
Method references
-
Optional
Java is not a pure functional language, but it encourages functional style.
🧩 Functional Programming Features in Java
🔹 Lambda Expressions
🔹 Functional Interfaces
Interface with one abstract method.
🔹 Streams API
Process collections in a functional way.
✔ Original list unchanged
✔ New list created
🔍 Does Stream Code Change State?
❌ No — it does not mutate the original data.
Only transformations occur, not mutation.
⚠️ Side Effects (Important Note)
This introduces side effects:
Printing is not pure, but Java allows controlled side effects.
🏭 Real-World Example: Order Processing
Requirement
-
Get completed orders
-
Apply discount
-
Calculate total amount
✔ Clear
✔ Readable
✔ Easy to parallelize
🧠 Why Functional Programming Is Useful
-
Less boilerplate code
-
Fewer bugs
-
Easy to test
-
Better concurrency support
-
Improved readability
❌ What Functional Programming Is NOT in Java
Java FP:
-
❌ Is not purely functional
-
❌ Allows mutable state
-
❌ Allows side effects
But it promotes safer coding practices.
🆚 Imperative vs Functional (Quick View)
Imperative
Functional
🎯 Interview-Ready Answer
Functional programming is a paradigm that emphasizes pure functions, immutability, and declarative code.
Java supports functional programming through lambdas, functional interfaces, and streams since Java 8.
📝 One-Line Summary
Functional programming in Java means transforming data using functions without changing the original state.
No comments:
Post a Comment