DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Redefining Java Object Equality
  • Java vs. Scala: Comparative Analysis for Backend Development in Fintech
  • Singleton: 6 Ways To Write and Use in Java Programming
  • How To Get Started With New Pattern Matching in Java 21

Trending

  • A Modern Stack for Building Scalable Systems
  • How To Introduce a New API Quickly Using Quarkus and ChatGPT
  • MCP Servers: The Technical Debt That Is Coming
  • Blue Skies Ahead: An AI Case Study on LLM Use for a Graph Theory Related Application
  1. DZone
  2. Coding
  3. Languages
  4. Understanding Functional Programming: A Quick Guide for Beginners

Understanding Functional Programming: A Quick Guide for Beginners

This quick and simple guide to functional programming concepts covers pure functions, immutability, and declarative coding for cleaner, predictable code.

By 
Sri Harshitha Yarra user avatar
Sri Harshitha Yarra
·
Sachin More user avatar
Sachin More
·
Dec. 10, 24 · Tutorial
Likes (8)
Comment
Save
Tweet
Share
9.2K Views

Join the DZone community and get the full member experience.

Join For Free

Imagine you're working on a complex puzzle. There are two ways to solve it:

  1. The first way: You keep rearranging all the pieces directly on the table, moving them around, and sometimes the pieces you've already arranged get disturbed. This is like traditional imperative programming, where we directly modify data and state as we go.

  2. The second way: For each step, you take a picture of your progress, and when you want to try something new, you start with a fresh copy of the last successful attempt. No previous work gets disturbed, and you can always go back to any of the prior states. This is functional programming — where we transform data by creating new copies instead of modifying existing data.

Functional programming isn't just another programming style — it's a way of thinking that makes your code more predictable, testable, and often, more readable. In this article, we'll break down functional programming concepts in a way that will make you say, "Ah, now I get it!"

What Makes Code "Functional"? 

Let's break down the core concepts that separate functional programming from traditional imperative (or "primitive") programming.

1. Pure Functions: The Heart of FP 

In functional programming, pure functions are like vending machines. Given the same input (money and selection), they always return the same output (specific snack). They don't:

  • Keep track of previous purchases
  • Modify anything outside themselves
  • Depend on external factors

Code examples:

Plain Text
 
// Impure function - Traditional approach
class Calculator {
    // This variable can be changed by any method, making it unpredictable
    private int runningTotal = 0;

    // Impure method - it changes the state of runningTotal
    public int addToTotal(int number) {
        runningTotal += number;  // Modifying external state
        return runningTotal;
    }
}

// Pure function - Functional approach
class BetterCalculator {
    // Pure method - only works with input parameters
    // Same inputs will ALWAYS give same outputs
    public int add(int first, int second) {
        return first + second;
    }
}

// Usage example:
Calculator calc = new Calculator();
System.out.println(calc.addToTotal(5));  // Output: 5
System.out.println(calc.addToTotal(5));  // Output: 10 (state changed!)

BetterCalculator betterCalc = new BetterCalculator();
System.out.println(betterCalc.add(5, 5));  // Always outputs: 10
System.out.println(betterCalc.add(5, 5));  // Always outputs: 10


2. Immutability: Treat Data Like a Contract 

In traditional programming, we often modify data directly. In functional programming, we treat data as immutable - once created, it cannot be changed. Instead of modifying existing data, we create new data with the desired changes.

Plain Text
 
// Traditional approach - Mutable List
public class MutableExample {
    public static void main(String[] args) {
        // Creating a mutable list
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");

        // Modifying the original list - This can lead to unexpected behaviors
        fruits.add("Orange");
        System.out.println(fruits);  // [Apple, Banana, Orange]
    }
}

// Functional approach - Immutable List
public class ImmutableExample {
    public static void main(String[] args) {
        // Creating an immutable list
        List<String> fruits = List.of("Apple", "Banana");

        // Instead of modifying, we create a new list
        List<String> newFruits = new ArrayList<>(fruits);
        newFruits.add("Orange");
        
        // Original list remains unchanged
        System.out.println("Original: " + fruits);      // [Apple, Banana]
        System.out.println("New List: " + newFruits);   // [Apple, Banana, Orange]
    }
}


3. Declarative vs. Imperative: The "What" vs. the "How"

Traditional programming often focuses on how to do something (step-by-step instructions). Functional programming focuses on what we want to achieve.

Plain Text
 
public class NumberProcessing {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);

        // Traditional approach (imperative) - Focusing on HOW
        List<Integer> evenNumbersImperative = new ArrayList<>();
        // Step by step instructions
        for (Integer number : numbers) {
            if (number % 2 == 0) {
                evenNumbersImperative.add(number);
            }
        }

        // Functional approach (declarative) - Focusing on WHAT
        List<Integer> evenNumbersFunctional = numbers.stream()
            // Just specify what we want: numbers that are even
            .filter(number -> number % 2 == 0)
            .collect(Collectors.toList());

        System.out.println("Imperative Result: " + evenNumbersImperative);
        System.out.println("Functional Result: " + evenNumbersFunctional);
    }
}


Why Choose Functional Programming? 

  1. Predictability: Pure functions always produce the same output for the same input, making code behavior more predictable.
  2. Testability: Pure functions are easier to test because they don't depend on external state.
  3. Debugging: When functions don't modify the external state, bugs are easier to track down.
  4. Concurrency: Immutable data and pure functions make concurrent programming safer and more manageable.

Common Functional Programming Patterns

Here's a quick look at some common patterns you'll see in functional programming:

Plain Text
 
public class FunctionalPatterns {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

        // 1. Map: Transform each number to its doubled value
        List<Integer> doubled = numbers.stream()
            .map(number -> number * 2)  // transforms each number
            .collect(Collectors.toList());
        System.out.println("Doubled: " + doubled);  // [2, 4, 6, 8, 10]

        // 2. Filter: Keep only even numbers
        List<Integer> evens = numbers.stream()
            .filter(number -> number % 2 == 0)  // keeps only even numbers
            .collect(Collectors.toList());
        System.out.println("Evens: " + evens);  // [2, 4]

        // 3. Reduce: Sum all numbers
        int sum = numbers.stream()
            .reduce(0, (a, b) -> a + b);  // combines all numbers into one
        System.out.println("Sum: " + sum);  // 15
    }
}


Conclusion

Remember: Just like taking pictures of your puzzle progress, functional programming is about creating clear, traceable transformations of your data. Each step is predictable, reversible, and clean.

Start small — try using map, filter, and reduce instead of for loops. Experiment with keeping your data immutable. Soon, you'll find yourself naturally thinking in terms of data transformations rather than step-by-step instructions.

Functional programming Data Types

Opinions expressed by DZone contributors are their own.

Related

  • Redefining Java Object Equality
  • Java vs. Scala: Comparative Analysis for Backend Development in Fintech
  • Singleton: 6 Ways To Write and Use in Java Programming
  • How To Get Started With New Pattern Matching in Java 21

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!